[英]How to replace key/value pairs in an object of two arrays of objects
我想將鍵 'id' 和它的值替換為 'type' 的屬性,其值為 'inc' 或 'exp'。 我還想從 exp 數組中的對象中刪除屬性“百分比”。 最后,我想將所有對象合並到一個數組中。
這就是我所做的,它具有預期的結果,但必須有一條捷徑來實現這一目標,代碼更少,更干凈。 謝謝!
const list = {
exp: [
{ id: 0, value: 57, percentage: 12 },
{ id: 1, value: 34, percentage: 10 },
],
inc: [
{ id: 1, value: 18 },
{ id: 1, value: 89 },
],
};
// Deep copy of list object
let newList = JSON.parse(JSON.stringify(list));
// Destructuring
const { exp, inc } = newList;
for (let obj of exp) {
obj.type = "exp";
delete obj.id;
delete obj.percentage;
}
for (let obj2 of inc) {
obj2.type = "inc";
delete obj2.id;
}
//Spread operator
newList = [...newList.exp, ...newList.inc];
console.log(newList);
您可以在Object.entries()的支持下使用flatMap
const list = { exp: [ { id: 0, value: 57, percentage: 12 }, { id: 1, value: 34, percentage: 10 }, ], inc: [ { id: 1, value: 18 }, { id: 1, value: 89 }, ], }; const res = Object.entries(list).flatMap(([type, values]) => values.map((value) => ({ value: value.value, type: type, })) ); console.log(res);
一步步
A = Object.entries(list)
// -->
[
[
"exp",
[
{ "id": 0, "value": 57, "percentage": 12 },
{ "id": 1, "value": 34, "percentage": 10 }
]
],
[
"inc",
[
{ "id": 1, "value": 18 },
{ "id": 1, "value": 89 }
]
]
]
B = A.map(...)
// -->
[
[
{ "value": 57, "type": "exp" },
{ "value": 34, "type": "exp" }
],
[
{ "value": 18, "type": "inc" },
{ "value": 89, "type": "inc" }
]
]
C = B.flat()
// -->
[
{ "value": 57, "type": "exp" },
{ "value": 34, "type": "exp" },
{ "value": 18, "type": "inc" },
{ "value": 89, "type": "inc" }
]
flatMap
是步驟 B 和 C 的組合( .map
然后.flat
)
如果value
是您想要的唯一屬性:
const list = { exp: [ { id: 0, value: 57, percentage: 12 }, { id: 1, value: 34, percentage: 10 } ], inc: [ { id: 1, value: 18 }, { id: 1, value: 89 } ] }; const newList = []; const types = Object.keys(list); types.forEach((type) => { list[type].forEach(({ value }) => { newList.push({ type, value }); }); }); console.log(newList); console.log(JSON.stringify(newList));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.