我有一組像這樣的物件:
let arr1 = [{
"ref": 1,
"index": "300",
"data": {
"id": 10,
"status": {
"code": "red"
}
}
}, {
"ref": 2,
"index": "301",
"data": {
"id": 20,
"status": {
"code": "blue"
}
}
}];
我想將status.code替換為另一個物件陣列中給出的那個:
let arr2 = [{
"id": 10,
"content": {
"name": "green"
}
}, {
"id": 20,
"content": {
"name": "yellow"
}
}];
我的想法是映射第一個陣列并使用 find 函式(或過濾器)回圈第二個陣列,當 ID 的匹配更改值但我遺漏了一些東西時,我怎樣才能做到這一點最優化性能和可讀性方法?
let res: any[];
res = arr2.map((x: any) =>
arr1.find((y: any) =>
(y.data.id === x.id) ? 'logic if match' : 'return'
));
uj5u.com熱心網友回復:
我會首先以arr2
更容易訪問的方式更改格式:(如果您可以輕松更改獲取此資料的方式,我認為會更好。否則,請按如下方式轉換資料。)
const idStatusCodeMap = {
"10": "green",
"20": "yellow"
}
我們這樣做是為了看看是否有idStatusCodeMap[10]
or idStatusCodeMap[anyId]
。這使得您可以只回圈遍歷,而不是和arr1
的嵌套回圈。然后,如有必要,回圈并替換顏色。如果假設在 上找不到新顏色,例如 for ,那么不要為此做任何事情。arr1
arr2
arr1
idStatusCodeMap
id = 30
let arr1 = [{
"ref": 1,
"index": "300",
"data": {
"id": 10,
"status": {
"code": "red"
}
}
}, {
"ref": 2,
"index": "301",
"data": {
"id": 20,
"status": {
"code": "blue"
}
}
}];
let arr2 = [{
"id": 10,
"content": {
"name": "green"
}
}, {
"id": 20,
"content": {
"name": "yellow"
}
}];
let idStatusCodeMap = {}
//transpiling arr2 to more performant hashMap
arr2.forEach(item => {
idStatusCodeMap[item.id] = item.content.name;
})
console.log(idStatusCodeMap);
arr1 = arr1.map(item => {
//if the id of an item in arr1 is found in code map, replace it with new value.
//if not found, it will skip.
if(idStatusCodeMap[item.data.id]) {
item.data.status.code = idStatusCodeMap[item.data.id]
}
return item;
})
console.log(arr1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488766.html
標籤:javascript 打字稿 目的 ecmascript-6 寻找
上一篇:如何將用戶輸入傳遞給類的物件?