我想过滤与models数组中的“model”键匹配的items数组对象,并将它们存储在数组中。我的努力取得了成功,但我对我的努力并不满意。有没有更好的方法来做到这一点?使用多个数组过滤嵌套的JSON对象并将过滤的对象存储在数组中
有关如何使用underscore.js和lodash执行操作的任何建议?或者使用本地JavaScript映射和过滤器功能?
JSON对象
{
"items": [
{
"model": "ooc0d",
"code": "2x4qr",
"price": 33
},
{
"model": "ruie9",
"code": "2f6gi",
"price": 22
},
{
"model": "aqu0d",
"code": "2f6gi",
"price": 21
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 25
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 29
}
],
"models": [
{
"model": "ruie9",
"year": 1998
},
{
"model": "ooc0d",
"year": 1991
},
{
"model": "aqu0d",
"year": 1994
},
{
"model": "ddebd",
"year": 1995
},
{
"model": "odq76",
"year": 1999
}
]
}
我的解决方案
const { models, items } = jsonData;
const newarray = [];
for(let i = 0; i < models.length; i++) {
for(let j = 0; j < items.length; j++) {
if(items[j].model===models[i].model) {
let obj = {
...items[j],
year: models[i].year
}
newarray.push(obj);
}
}
}
您访问'id'财产,但有你的JSON – quirimmo
不跟踪id属性哎呀对不起。刚刚纠正 – 1033
@创建了这个[基准](https://jsfiddle.net/sf5jtru6/)与我Umair和Pankaj。 Pankaj获胜:) –