如何只显示包含对象的数组?

时间:2017-03-07 12:39:41

标签: javascript arrays

我尝试从数组中过滤掉一些元素。因此,如果在数组中找到元素键,则仅显示包含该元素的那些数组。

{"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":[]}

所以在这种情况下,如果我的键是“h”,它应该只显示第一个和第三个数组。

我的代码现在看起来像这样,但我很难找到一种只显示那些的方法。

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 个答案:

答案 0 :(得分:3)

您可以使用过滤器来排除与您的参数不匹配的对象

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

仔细看看how the in-operator works in javascript。 它不检查给定数组是否包含此属性,它检查数组是否具有索引option

我猜你要找的是类似s.Data.results[i].result.indexOf(option) !== -1)的内容(请查看this post,了解contains()等效变种的更多详情

相关问题