gpt4 book ai didi

javascript - 如何在 JavaScript 对象中过滤数组中的元素

转载 作者:行者123 更新时间:2023-11-30 06:53:23 26 4
gpt4 key购买 nike

如果我有这样一个 JavaScript 对象:

{"products":
[
{
"id":"6066157707315577",
"reference_prefix":"BB",
"name":"BeanieBaby",
"product_line":false,
"has_ideas":true
},
{
"id":"6066197229601550",
"reference_prefix":"BBAGS",
"name":"BlackBags",
"product_line":false,
"has_ideas":false
}
],
"pagination": {
"total_records":4,
"total_pages":1,
"current_page":1
}
}

我如何在 js 中编写一个函数来遍历每一对并仅返回数组中 has_ideas === true 的元素?

我已经从这个开始,但我被卡住了。显然我对此很陌生。任何帮助表示赞赏。

product: function(mybundle) {

var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
var obj = json[i];

if (json[i].id === "has_ideas" && json[i].value === true) {
return json;
}
return [];
}
}

最佳答案

您可以通过简单地检查该属性来过滤掉每一对:

var json = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}

var stuff = json.products.filter(function(obj) {
return obj.has_ideas === true
});

console.log(stuff);

演示:http://jsfiddle.net/bsyk18cb/

关于javascript - 如何在 JavaScript 对象中过滤数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26248389/

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