[英]How to group an array of objects by key?
How do you group an array of objects by an object key to create a new array of objects based on the grouping?如何通过对象键对对象数组进行分组以基于分组创建新的对象数组? For example, I have an array of car objects:
例如,我有一个汽车对象数组:
const array = [
{red: [ {height: 50} ]},
{green: [ {height: 20} ]},
{blue: [ {height: 30} ]},
{blue: [ {height: 40} ]},
{red: [ {height: 10} ]},
{green: [ {height: 60} ]}
]
I want to create a new array of objects.(key is color)我想创建一个新的对象数组。(关键是颜色)
const result = [
{red: [{height: 50}, {height: 10}]},
{green: [{height: 20}, {height: 60}]},
{blue: [{height: 30}, {height: 40}]}
]
I tried to use lodash.groupBy, however I don't know how to solve this problem at all.我尝试使用 lodash.groupBy,但是我根本不知道如何解决这个问题。
Using array reduce you can iterate data and calculate result object.使用 array 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);
You can use lodash's _.mergeWith()
to combine the objects with the same key, and then use _.map()
to convert it back to an array:您可以使用 lodash 的
_.mergeWith()
将具有相同键的对象组合在一起,然后使用_.map()
将其转换回数组:
const array = [{"red":[{"height":50}]},{"green":[{"height":20}]},{"blue":[{"height":30}]},{"blue":[{"height":40}]},{"red":[{"height":10}]},{"green":[{"height":60}]}] const fn = _.flow([ arr => _.mergeWith({}, ...arr, (o, s) => _.isArray(o) ? o.concat(s) : s), objs => _.map(objs, (v, k) => ({ [k]: v })) ]) const result = fn(array) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.