Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:

                          {
                            "data": {
                              "value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
                              "partnerId": 1
                            }
                          },

So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?

console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.

23 thoughts on “Filter Array Using Partial String Match in Javascript”

  1. The problem is somewhere else. The code you’ve tried should work to find if a value contains a string – I’ve added it the snippet below and you’ll see it works.

    The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.

    const data = {
      "value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
    };
    
    console.log('includes?', data.value.includes('parent_sku'));
    Reply
  2. You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.

    try:

    "data": {
        "value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
        "partnerId": 1
    }
    
    Reply

Leave a Comment