我想過濾與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獲勝:) –