[英]Update an array of objects using another array
我需要根據 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 中還有其他方法嗎?
由於問題已更新,這實際上只是@Giorgi Moniava 答案的擴展。 我認為您應該將他的答案標記為已接受的答案。 基本上你需要做的就是檢查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)
你不需要 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
是否在對象內部會更快(與檢查數組內部相比)。 但實際上,在大多數情況下,您不應該注意到差異。
試試這個,使用帶有包含功能的地圖功能。 希望這個答案能給出你的實際結果。 如果沒有,請給我評論,我會給你另一個答案。
const found = a.map(function(mapData){
(marked.includes(mapData.id)) ? mapData.active = true : '';
return mapData;
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.