要按术语分组并获取嵌套数组属性的计数,可以使用JavaScript的reduce和map函数。以下是一个解决方法的代码示例:
const data = [
{
term: "A",
attributes: [
{ name: "attr1", count: 5 },
{ name: "attr2", count: 10 },
],
},
{
term: "B",
attributes: [
{ name: "attr1", count: 3 },
{ name: "attr2", count: 8 },
],
},
{
term: "A",
attributes: [
{ name: "attr1", count: 2 },
{ name: "attr2", count: 7 },
],
},
];
const result = data.reduce((acc, curr) => {
const existingTerm = acc.find((item) => item.term === curr.term);
if (existingTerm) {
curr.attributes.forEach((attr) => {
const existingAttr = existingTerm.attributes.find(
(item) => item.name === attr.name
);
if (existingAttr) {
existingAttr.count += attr.count;
} else {
existingTerm.attributes.push(attr);
}
});
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(result);
这个代码示例中的data
数组包含多个对象,每个对象都有一个term
属性和一个attributes
属性,attributes
属性是一个嵌套的数组,包含name
属性和count
属性。我们要按term
属性分组,并将相同term
的attributes
的count
属性进行累加。
使用reduce
函数,我们首先创建一个空数组acc
作为累加器。然后遍历原始数组data
,对每个对象进行处理。如果当前对象的term
属性在累加器数组中已存在,则遍历当前对象的attributes
数组,并检查每个属性的name
是否已存在于累加器数组中的相应term
对象的attributes
数组中。如果已存在,则将count
属性进行累加;如果不存在,则将该属性添加到累加器数组中的相应term
对象的attributes
数组中。如果当前对象的term
属性在累加器数组中不存在,则将该对象添加到累加器数组中。
最后,将累加器数组打印出来,即可得到按术语分组并获取嵌套数组属性的计数的结果。