[英]Group and sum of an array of objects based on number key
I am trying to create a statistical pie chart. 我正在尝试创建统计饼图。 As a http response
i am getting a list from server using which i need to draw a pie chart. 作为http response
我从服务器获取列表,使用该列表需要绘制饼图。
For example: Data received: 例如:收到的数据:
[{1: 9, 2: 7}, {3:8, 2: 1}, {1:8, 5:9}, {2:3, 3:1}]
This is the desired output: 这是所需的输出:
[{x: 1, y: 17}, {x: 2, y:10}, {x: 3, y: 9}, {x: 5, y: 9}]
Please note: x is the key and y is sum of similar key values 请注意:x是键,y是相似键值的总和
I have tried data.forEach((item, index) => {})
. 我已经尝试过data.forEach((item, index) => {})
。 After writing this, I am actually getting no lead about how I can combine Object.keys(item)
, Object.values(item)
and Object.values(item).reduce((a,b)=> return a+b;)
写完这篇文章后,我实际上对如何组合Object.keys(item)
, Object.values(item)
和Object.values(item).reduce((a,b)=> return a+b;)
This may sound silly question, but any help would be appreciated. 这听起来可能是愚蠢的问题,但任何帮助将不胜感激。 :) :)
You could reduce
the array. 您可以reduce
阵列。 Create an accumulator object with each number as key and and object with x
and y
keys as it's value. 创建一个累加器对象,每个数字作为键,并创建带有x
和y
键作为其值的对象。 Loop through each object and update the y
value based on the number. 循环遍历每个对象,并根据数字更新y
值。 Then use Object.values()
on the object returned to get the values of the accumulator as an array 然后在返回的对象上使用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))
You could look for same key and update or insert a new object. 您可以寻找相同的键并更新或插入新对象。
This approach does not change the order of the keys. 此方法不会更改键的顺序。
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 => ox === 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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.