[英]How to replace key/value pairs in an object of two arrays of objects
I would like to replace the key 'id' and it's value with the property of 'type' with a value of 'inc'or 'exp'.我想将键 'id' 和它的值替换为 'type' 的属性,其值为 'inc' 或 'exp'。 I also want to delete the property 'percentage' from the objects in the exp array.
我还想从 exp 数组中的对象中删除属性“百分比”。 In the end I want to merge al the objects into one array.
最后,我想将所有对象合并到一个数组中。
This is what I did, it has the desired outcome but there must be a shortcut to achieve this, with less code and cleaner.这就是我所做的,它具有预期的结果,但必须有一条捷径来实现这一目标,代码更少,更干净。 Thanks!
谢谢!
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);
You could use flatMap in the support of Object.entries()您可以在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);
Step by step一步步
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
is the combination of step B and C ( .map
then .flat
) flatMap
是步骤 B 和 C 的组合( .map
然后.flat
)
If value
is the only property you want:如果
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.