Click here to Skip to main content
14,875,778 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please help, I have an array of objects :

[ 
  { key : 'Fruit', name : 'Apple' },
  { key : 'Fruit', name : 'Orange' },
  { key : 'Drink', name : 'Coke' },
  { key : 'Drink', name : 'Pepsi' },
  { key : 'Candy', name : 'Chocolate' }
];


And I want to convert to other array like this:
[ 
  { key : 'Fruit', name : [ 'Apple', 'Orange' ] },
  { key : 'Drink', name : [ 'Coke', 'Pepsi' ] },
  { key : 'Candy', name : [ 'Chocolate' ] },
];


What I have tried:

I have tried some functions which I searched on the internet but it didn't work well
Posted
Updated 2-Mar-21 21:23pm

1 solution

Try something like this:
JavaScript
const input = [ 
  { key : 'Fruit', name : 'Apple' },
  { key : 'Fruit', name : 'Orange' },
  { key : 'Drink', name : 'Coke' },
  { key : 'Drink', name : 'Pepsi' },
  { key : 'Candy', name : 'Chocolate' }
];

const groupedData = input.reduce((agr, item) => {
	let x = (agr[item.key] ??= { key: item.key, name: [] });
	x.name.push(item.name)
	return agr;
}, {});

const result = Object.entries(groupedData).reduce((agr, item) => {
	agr.push(item[1]);
	return agr;
}, []);
Demo[^]
Array.prototype.reduce() - JavaScript | MDN[^]
Object.entries() - JavaScript | MDN[^]
Logical nullish assignment (??=) - JavaScript | MDN[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900