如何展平对象的分层数组+JS中子项的总和值
How to flatten an hierarchical array of objects + sum values from childs in JS
这个让我很头疼,不知如何实现重组这个对象数组:
const obj = [
{
id: 10,
name: "foo", // parent
value: 20
}, {
id: 11,
name: "foo - 1", // child
value: 2
}, {
id: 12,
name: "foo - 2", // child
value: 4
}, {
id: 20,
name: "bar",// parent
value: 10
}, {
id: 21,
name: "bar - 1", // child
value: 8
}
];
对此:
const desired = [
{
id: 10,
name: "foo",
value: 26 // "foo" + "foo - 1" + "foo - 2"
}, {
id: 20,
name: "bar",
value: 18 // "bar" + "bar - 1"
}
];
我想对各个子项的值求和,然后用结果更新父项的值,然后删除子项。
实施应该符合 ES6+ 标准,并且没有像 lodash(或类似)这样的库。
使用reduce
按名称关键字分组(通过应用正则表达式),然后取Object.values
得到数组数据
const arr = [ { id: 10, name: "foo", value: 20 }, { id: 11, name: "foo - 1", value: 2 }, { id: 12, name: "foo - 2", value: 4 }, { id: 20, name: "bar", value: 10 }, { id: 21, name: "bar - 1", value: 8 }];
const result = Object.values(arr.reduce((a,e)=>{
const name = e.name.match(/\w+/g)[0];
// OR also you can split like e.name.split("-")[0]
a[name] ??= {...e, name, value:0};
a[name].value+=e.value;
return a;
},{}));
console.log(result);
这个让我很头疼,不知如何实现重组这个对象数组:
const obj = [
{
id: 10,
name: "foo", // parent
value: 20
}, {
id: 11,
name: "foo - 1", // child
value: 2
}, {
id: 12,
name: "foo - 2", // child
value: 4
}, {
id: 20,
name: "bar",// parent
value: 10
}, {
id: 21,
name: "bar - 1", // child
value: 8
}
];
对此:
const desired = [
{
id: 10,
name: "foo",
value: 26 // "foo" + "foo - 1" + "foo - 2"
}, {
id: 20,
name: "bar",
value: 18 // "bar" + "bar - 1"
}
];
我想对各个子项的值求和,然后用结果更新父项的值,然后删除子项。
实施应该符合 ES6+ 标准,并且没有像 lodash(或类似)这样的库。
使用reduce
按名称关键字分组(通过应用正则表达式),然后取Object.values
得到数组数据
const arr = [ { id: 10, name: "foo", value: 20 }, { id: 11, name: "foo - 1", value: 2 }, { id: 12, name: "foo - 2", value: 4 }, { id: 20, name: "bar", value: 10 }, { id: 21, name: "bar - 1", value: 8 }];
const result = Object.values(arr.reduce((a,e)=>{
const name = e.name.match(/\w+/g)[0];
// OR also you can split like e.name.split("-")[0]
a[name] ??= {...e, name, value:0};
a[name].value+=e.value;
return a;
},{}));
console.log(result);