我要加anotherarray
其中history_id === 2
到firstarray
其中id == 2
進入history: []
陣列。但是我的大腦越來越瘋狂,試圖找到任何解決方案。我已經嘗試underscore.js,但我甚至不知道如何實現它。由ID擴展Nodejs陣列
let firstarray = {
settings: {
time: "timestamp"
},
games: [
{
id: 1,
name: "test1",
history: []
}, {
id: 2,
name: "test3",
history: []
}
]
};
let anotherray = [{
id: 11,
history_id: 2,
color: 'red'
}, {
id: 12,
history_id: 2,
color: 'blue'
}, {
id: 13,
history_id: 1,
color: 'white'
}];
結果應該是這樣的:
let firstarray = {
settings: {
time: "timestamp"
},
games: [
{
id: 1,
name: "test1",
history: [{
id: 13,
history_id: 1,
color: 'white'
}]
}, {
id: 2,
name: "test3",
history: [{
id: 11,
history_id: 2,
color: 'red'
}, {
id: 12,
history_id: 2,
color: 'blue'
}]
}
]
};
我真的堅持現在..我真的不知道我能應付:(
編輯:我發現我自己的解決方案:
for(let i = 0; i < anotherray.length; i++) {
firstarray.games.forEach(function(key,value) {
if(anotherray[i].history_id === key.id) {
firstarray.games[value].history.push(
{
color: anotherray[i].color
}
)
}
});
}
console.log(JSON.stringify(firstarray));
這不是有效的。對於每一款遊戲,你都要過濾另一個數組。你可以過濾一次'anotherarray',保存它,然後用它來追加'id == 2'對象的'歷史'數組' –
所以你認爲硬編碼的值更好?如果還有更多的ID可以找到呢? @TurkhanBadalov。你的方法只適用於一個ID,OP在問題中要求兩個。 – baao
你總是可以用一些變量'k'來回報'2' :)問題是最優性。但我想我們只是以不同的方式理解這個問題。你的函數適用於一般情況,當所有具有相同'history_id'和'id'的項目都應該被分配。但我認爲這個問題是關於一次性請求的。 –