基于数字键的对象数组的分组和总和
Group and sum of an array of objects based on number key
我正在尝试创建统计饼图。作为一名 http response
我正在从服务器获取一个列表,我需要使用它来绘制饼图。
例如:收到的数据:
[{1: 9, 2: 7}, {3:8, 2: 1}, {1:8, 5:9}, {2:3, 3:1}]
这是期望的输出:
[{x: 1, y: 17}, {x: 2, y:10}, {x: 3, y: 9}, {x: 5, y: 9}]
请注意:x 是键,y 是相似键值的总和
我试过了data.forEach((item, index) => {})
。写完这篇文章后,我实际上对如何组合 Object.keys(item)
、Object.values(item)
和 Object.values(item).reduce((a,b)=> return a+b;)
毫无头绪
这个问题听起来可能很愚蠢,但我们将不胜感激。 :)
您可以 reduce
the array. Create an accumulator object with each number as key and and object with x
and y
keys as it's value. Loop through each object and update the y
value based on the number. Then use Object.values()
在返回的对象上获取累加器的值作为数组
const input = [{1: 9, 2: 7}, {3:8, 2: 1}, {1:8, 5:9}, {2:3, 3:1}]
const grouped = input.reduce((acc, obj) => {
for (const x in obj) {
acc[x] = acc[x] || { x , y: 0 }
acc[x].y += obj[x]
}
return acc;
}, {})
console.log(Object.values(grouped))
您可以查找相同的键并更新或插入新对象。
这种方法不会改变键的顺序。
var data = [{ 1: 9, 2: 7 }, { 3: 8, 2: 1 }, { 1: 8, 5: 9 }, { 2: 3, 3: 1 }] ,
result = data.reduce((r, o) => {
Object.entries(o).forEach(([x, y]) => {
var temp = r.find(o => o.x === x);
if (temp) temp.y += y;
else r.push({ x, y });
});
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
我正在尝试创建统计饼图。作为一名 http response
我正在从服务器获取一个列表,我需要使用它来绘制饼图。
例如:收到的数据:
[{1: 9, 2: 7}, {3:8, 2: 1}, {1:8, 5:9}, {2:3, 3:1}]
这是期望的输出:
[{x: 1, y: 17}, {x: 2, y:10}, {x: 3, y: 9}, {x: 5, y: 9}]
请注意:x 是键,y 是相似键值的总和
我试过了data.forEach((item, index) => {})
。写完这篇文章后,我实际上对如何组合 Object.keys(item)
、Object.values(item)
和 Object.values(item).reduce((a,b)=> return a+b;)
这个问题听起来可能很愚蠢,但我们将不胜感激。 :)
您可以 reduce
the array. Create an accumulator object with each number as key and and object with x
and y
keys as it's value. Loop through each object and update the y
value based on the number. Then use Object.values()
在返回的对象上获取累加器的值作为数组
const input = [{1: 9, 2: 7}, {3:8, 2: 1}, {1:8, 5:9}, {2:3, 3:1}]
const grouped = input.reduce((acc, obj) => {
for (const x in obj) {
acc[x] = acc[x] || { x , y: 0 }
acc[x].y += obj[x]
}
return acc;
}, {})
console.log(Object.values(grouped))
您可以查找相同的键并更新或插入新对象。
这种方法不会改变键的顺序。
var data = [{ 1: 9, 2: 7 }, { 3: 8, 2: 1 }, { 1: 8, 5: 9 }, { 2: 3, 3: 1 }] ,
result = data.reduce((r, o) => {
Object.entries(o).forEach(([x, y]) => {
var temp = r.find(o => o.x === x);
if (temp) temp.y += y;
else r.push({ x, y });
});
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }