0

I try to filter some elements from my array. So if the element key is found in array show only those arrays that include that.

{"result":["b", "f", "h"], "model":3, "path":3, "resultnumber":56, "otherproducts":["e"]},
{"result":["b", "f", "j"], "model":3, "path":3, "resultnumber":58, "otherproducts":["e"]},  
{"result":["b", "g", "h"], "model":11, "path":3, "resultnumber":59, "otherproducts":[]}

So in this case if my key is "h" it should show only first and third array.

My code looks like this now but I am stuck trying to find a way to display only those.

for (var i = 0; i < s.Data.results.length; i++){
     var checkObject = s.Data.results[i].path == 3;
     console.log(checkObject);
     if (checkObject){
        if(option in s.Data.results[i].result){
            console.log(s.Data.results[i].result);
        }
     }
}

2 Answers2

3

You could use filter, to exclude the objects that don't match your parameters

var data = [{"result":["b", "f", "h"], "model":3, "path":3, "resultnumber":56, "otherproducts":["e"]},
{"result":["b", "f", "j"], "model":3, "path":3, "resultnumber":58, "otherproducts":["e"]},
{"result":["b", "g", "h"], "model":11, "path":3, "resultnumber":59, "otherproducts":[]}]

var filtered = data.filter( ({ result }) => result.indexOf("h") > -1)

console.log(filtered);
alebianco
  • 2,475
  • 18
  • 25
1

Take a closer look at how the in-operator works in javascript. It doesn't check if the given array contains this property, it checks whether the array has the index option.

I guess what you are looking for is something like s.Data.results[i].result.indexOf(option) !== -1) (Take a look at this post, for more details on variants of contains() equivalents)

Community
  • 1
  • 1
jdepoix
  • 475
  • 1
  • 4
  • 11