gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:56:36 27 4
gpt4 key购买 nike

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

{"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);
}
}
}

最佳答案

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

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);

关于javascript - 如何只显示包含对象的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42648571/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com