如何按键对对象数组进行分组?

编程入门 行业动态 更新时间:2024-10-27 14:30:04
本文介绍了如何按键对对象数组进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 如何按对象键对对象数组进行分组,以根据分组创建新的对象数组? 例如,我有一个汽车对象数组:

const array = [ {red: [ {height: 50} ]}, {green: [ {height: 20} ]}, {blue: [ {height: 30} ]}, {blue: [ {height: 40} ]}, {red: [ {height: 10} ]}, {green: [ {height: 60} ]} ]

我要创建一个新的对象数组。(键为颜色)

const result = [ {red: [{height: 50}, {height: 10}]}, {green: [{height: 20}, {height: 60}]}, {blue: [{height: 30}, {height: 40}]} ]

我尝试使用listash.groupBy,但是我根本不知道如何解决此问题。

推荐答案

使用数组Reduce可以迭代数据并计算结果对象。

const array = [ { 'red': [ { height: 50 } ] }, { 'green': [ { height: 20 } ] }, { 'blue': [ { height: 30 } ] }, { 'blue': [ { height: 40 } ] }, { 'red': [ { height: 10 } ] }, { 'green': [ { height: 60 } ] } ]; const res = array.reduce((acc, element) => { // Extract key and height value array const [key, heightValue] = Object.entries(element)[0]; // Get or create if non-exist, and push height value from array, index 0 (acc[key] || (acc[key] = [])).push(heightValue[0]); return acc; }, {}); console.log(res);

更多推荐

如何按键对对象数组进行分组?

本文发布于:2023-11-30 05:52:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   按键   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!