gpt4 book ai didi

javascript - 根据 Javascript 中的另一个对象过滤对象数组

转载 作者:行者123 更新时间:2023-11-30 15:40:11 24 4
gpt4 key购买 nike

我有一个对象数组

var data = [
{
"body_focus": "upper",
"difficulty": "three",
"calories_min": "122",
"calories_max": "250"
},
{
"body_focus": "upper",
"difficulty": "three",
"calories_min": "150",
"calories_max": "280"
},
{
"body_focus": "lower",
"difficulty": "two",
"calories_min": "100",
"calories_max": "180"
},
{
"body_focus": "total",
"difficulty": "four",
"calories_min": "250",
"calories_max": "350"
}
]

我想根据另一个对象过滤该对象数组

var myObj = {
"upper": true,
"three": true
}

现在 myObj 有一个键 "upper""three" 并且它们的值为 true。因此,基于这些值,我想创建一个函数来获取 data 数组中的所有对象,其键 "body_focus" 的值为 "upper""difficulty" 键,其值为 "three"

所以函数应该只返回这些对象

[
{
"body_focus": "upper",
"difficulty": "three",
"calories_min": "122",
"calories_max": "250"
},
{
"body_focus": "upper",
"difficulty": "three",
"calories_min": "150",
"calories_max": "280"
}
]

这就是我试图解决问题的方式

var entry;
var found = [];
for (var i = 0; i < data.length; i++) {
entry = data[i];
for(var key in myObj) {
if(entry.body_focus.indexOf(key) !== -1) {
found.push(entry);
break;
}
}
}

我上面的代码只检查键 body_focus ,那么如何检查 body_focusdifficulty 呢?这可能看起来很愚蠢,但我已经被困了几个小时而且找不到解决方案

最佳答案

您可以使用一个对象进行搜索,它提供键和所需的值,例如

search = {
body_focus: "upper",
difficulty: "three"
}

然后遍历数组并使用实际对象的值检查 search 的所有属性。如果所有搜索条件都匹配,则返回 true

var data = [{ body_focus: "upper", difficulty: "three", calories_min: "122", calories_max: "250" }, { body_focus: "upper", difficulty: "three", calories_min: "150", calories_max: "280" }, { body_focus: "lower", difficulty: "two", calories_min: "100", calories_max: "180" }, { body_focus: "total", difficulty: "four", calories_min: "250", calories_max: "350" }],
search = { body_focus: "upper", difficulty: "three" },
result = data.filter(function (o) {
return Object.keys(search).every(function (k) {
return o[k] === search[k];
});
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 根据 Javascript 中的另一个对象过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40933730/

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