我需要根據 ES6 中的另一個陣列更新物件陣列。例子
let a = [
{ id : 23, active :false, status:"" },
{ id : 33, active :false, status:"" },
{ id : 167, active :false, status:"" },
{ id : 18, active :false, status:"" },
{ id : 200, active :false, status:"" },
]
我的第二個包含物件的陣列
let marked = [167,33,23];
預期結果如下
let a = [
{ id : 23, active :true, status:"updated"},
{ id : 33, active :true, status:"updated" },
{ id : 167, active :true, status:"updated" },
{ id : 18, active :false, status:"" },
{ id : 200, active :false, status:"" },
]
請讓我知道如何獲得預期的結果。我們在 lodash 中還有其他方法嗎?
uj5u.com熱心網友回復:
你不需要 lodash,你可以這樣做:
let a = [{
id: 23,
active: false
},
{
id: 33,
active: false
},
{
id: 167,
active: false
},
{
id: 18,
active: false
},
{
id: 2,
active: false
},
]
let marked = [167, 33, 23];
let result = a.map(x => ({
...x,
active: marked.includes(x.id)
}))
console.log(result)
如果您遍歷marked陣列并將其元素存盤在物件中,則可以加快速度。然后在map檢查元素x.id是否在物件內部時會更快(與檢查陣列內部相比)。但實際上,在大多數情況下,您不應該注意到差異。
uj5u.com熱心網友回復:
由于問題已更新,這實際上只是@Giorgi Moniava 答案的擴展。我認為您應該將他的答案標記為已接受的答案。基本上,您需要做的就是檢查 for 的值active是真還是假。如果為真,則將狀態設定為updated否則,將狀態設定為空字串。
let a = [
{ id : 23, active :false, status:"" },
{ id : 33, active :false, status:"" },
{ id : 167, active :false, status:"" },
{ id : 18, active :false, status:"" },
{ id : 200, active :false, status:"" },
]
let marked = [167,33,23];
let result = a.map(obj => {
const isActive = marked.includes(obj.id);
const status = isActive ? 'updated' : '';
return {
...obj,
active: isActive,
status: status
}
})
console.log(result)
uj5u.com熱心網友回復:
試試這個,使用帶有包含功能的地圖功能。希望這個答案能給出你的實際結果。如果沒有,那么評論給我,我會給你另一個答案。
const found = a.map(function(mapData){
(marked.includes(mapData.id)) ? mapData.active = true : '';
return mapData;
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334117.html
標籤:javascript 数组 目的 ecmascript-6 洛达什
上一篇:我沒有得到最小值,它顯示為0,但在Math.max()的情況下它顯示正確的最大值,為什么會這樣?
下一篇:如何比較保留鍵的陣列值?
