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.
Using array reduce you can iterate data and calculate result object.
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:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.