问题描述
我有一个Javascript对象数组。每个对象都包含一个数组data
,在这里值得关注。我想减少所有具有相同名称的对象的数组(不同的id无关紧要,因为以后我想在图中绘制数据)。
norm.series = [
{ id: "qah01",name: "Bingo",data: [ ["date1",1.5] ] },{ id: "qah02",name: "Combo",data: [ ["date2",2.5] ] },{id: "qah03",0.5],["date3",1.2],["date4",2.0] ] },{ id: "qah04",name: "Sango",data: [ ["date7",3.2],["date8",2.8] ] }
]
What I yould like is the following:
norm.series [
{ id: "qah01",data: [ [date1,2.0],[date3,[date4,data: [ [date2,data: [ [date7,[date8,2.8] ] }
]
这是我到目前为止所做的:
const result = norm.series.reduce((acc,d) => {
const found = acc.find((a,index) => a.data[index][0] === d.data[index][0]);
const datanew = a.data[index][1] + d.data[index][1];
if (!found) {
acc.push({id: d.id,name:d.name,data: d.data})
}
else {
found.data.push(datanew);
}
return acc;
},[]);
解决方法
您可以使用Array.reduce
方法获得结果。
在Array.reduce
内部,您可以使用Array.findIndex
找到匹配的值,并为此创建一个处理程序。
const input = [
{ id: "qah01",name: "Bingo",data: [ [ 'date1',1.5 ] ] },{ id: "qah02",name: "Combo",data: [ [ 'date2',2.5 ] ] },{ id: "qah03",0.5 ],[ 'date3',1.2 ],[ 'date4',2.0 ] ] },{ id: "qah04",name: "Sango",data: [ [ 'date7',3.2 ],[ 'date8',2.8 ] ] }
];
const output = input.reduce((acc,cur) => {
const matchedIndex = acc.findIndex(({ name }) => name === cur.name);
if (matchedIndex >= 0) {
acc[matchedIndex].data = acc[matchedIndex].data.concat(cur.data).reduce((tor,curV) => {
const matchedDataInd = tor.findIndex(([dateName,dateValue]) => dateName === curV[0]);
if (matchedDataInd >= 0) {
tor[matchedDataInd][1] += curV[1];
return tor;
} else {
return [ ...tor,curV ];
}
},[]);
return acc;
} else {
return [ ...acc,cur ];
}
},[]);
console.log(output);