javascript - 如何按键对一组对象进行分组?
问题描述
如何通过对象键对对象数组进行分组,以根据分组创建新的对象数组?例如,我有一个汽车对象数组:
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}]}
]
我尝试使用 lodash.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);
推荐阅读
- angular - Angular - 使用 FromBody 字符串调用 web api HttpPost - 正文始终为空
- excel - 基于Excel数据操作表单的IE脚本
- java - 简单的 servlet 在 Tomcat/9.0.14 中遇到问题,出现错误“源服务器未找到当前表示..”
- c# - 用随机值填充空的 Guid 列表的最简单方法
- php - How to change position of login or register succesfull message?
- apache - Apache wicketStuff-GMap Api
- php - 可以将 PHP 扩展从 Docker“隧道”到外部?
- jquery - 当我单击第一个 div 以外的另一个 div 时我会做什么,然后第一个 div 的 css 将消失?
- c# - C# BufferedStream - 是否有可能知道进步?
- python - SQLITE 何时将数据写入驱动器?