我有2個對象數組:itemsList和itemsFetched。每個數組內的所有對象都具有相同的結構(鍵/值的數量)。其中一個按鍵具有相同的 '意義',但不同的名稱(ITEM_ID上itemsList,ID上itemsFetched)。他們的價值觀是一樣的。過濾器和克隆對象屬性
我需要過濾itemsList陣列,只留下那有ITEM_ID值等於ID值上itemsFetched的對象。然後從itemsDetched數組(其與item_id = id匹配)複製(添加)鍵/值count到過濾數組。
我有一個工作代碼,但我確定它不是解決此問題的最佳方法。我已經問過類似的問題了(關於'filter'部分)解決了我的問題,但由於我必須在過濾之後添加'count'部分,所以我最終重構了整個問題。
itemsList(樣品)
[
{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
},
{
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
},
{
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
},
{
"id": 401,
"name": "Incense",
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 901,
"name": "Incubator (Unlimited)",
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}
]
itemsFetched(樣品)
[
{
"item_id": 1,
"count": 50,
"unseen": true
},
{
"item_id": 401,
"count": 2,
"unseen": true
},
{
"item_id": 901,
"count": 1,
"unseen": true
}
]
resultArray(我想要的到底)
[
{
"id": 1,
"name": "Pokeball",
"count": 50,
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png",
},
{
"id": 401,
"name": "Incense",
"count": 2,
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 901,
"name": "Incubator (Unlimited)",
"count": 1,
"img": "http://www.serebii.net/pokemongo/items/eggincubator.png"
}
]
我現在的代碼(工作)
let arr = [];
itemsFetched.forEach((item) => {
itemsList.forEach((item2) => {
if (item.item_id === item2.id) {
arr.push({
"id": item.item_id,
"name": item2.name,
"count": item.count,
"img": item2.img
});
}
});
});
PS:我可以使用ES6/7語法/功能。
最好在服務器上做這個處理。總是返回格式化到瀏覽器的數據。然後,您不必在每個需要此數據的頁面上執行相同的數據操作。 – Luke101
是的,我意識到這一點。這是服務器端完成的。其中一個數組位於json文件及其模板上,另一個是對外部api調用的響應。 – nip
他試圖從數組中獲取id。這裏--- >> if(itemsFetched.item_id === itemsList.id) –