In this blog post, I will show you some cool ways to convert an object array to a dictionary i.e key-value pair. In other ways group the object by the key and return the data
For example, I have the following list of objects which contains the data of the mobile phone.
const applePhones = [
{ name: 'iPhone 12', price: 799,company:'Apple' },
{ name: 'iPhone 12 Pro', price: 999,company:'Apple' },
{ name: 'iPhone 12 Pro Max', price: 1099,company:'Apple' },
{ name: 'iPhone 12 mini', price: 699,company:'Apple' },
{ name: 'iPhone 11', price: 599,company:'Apple' },
{ name: 'Samsung Galaxy', price: 699,company:'Sumsung' },
{ name: 'Samsung Galaxy S20', price: 799,company:'Sumsung' },
{ name: 'Samsung Galaxy S20+', price: 899,company:'Sumsung' },
{ name: 'Samsung Galaxy S20 Ultra', price: 999,company:'Sumsung' },
];
Now I want to group the data by company name as shown below. You can see that data is grouped by company name.
{ 'Apple' : [ { name: 'iPhone 12', price: 799, company: 'Apple' },
{ name: 'iPhone 12 Pro', price: 999, company: 'Apple' },
{ name: 'iPhone 12 Pro Max', price: 1099, company: 'Apple' },
{ name: 'iPhone 12 mini', price: 699, company: 'Apple' },
{ name: 'iPhone 11', price: 599, company: 'Apple' } ],
'Samsung' : [ { name: 'Samsung Galaxy', price: 699, company: 'Samsung' },
{ name: 'Samsung Galaxy S20', price: 799, company: 'Samsung' },
{ name: 'Samsung Galaxy S20+', price: 899, company: 'Samsung' },
{ name: 'Samsung Galaxy S20 Ultra',
price: 999,
company: 'Sumsung' } ] }
There are multiple ways to solve the above problem but here I will show you two ways. The first one using the JavaScript reduce
method and a second one uses ES6 Map
Using Reduce
const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
return result;
}, {});
}
Using Map
const groupPhones = (phones) => {
const map = new Map();
phones.forEach((phone) => {
const company = phone.company;
if (!map.has(company)) {
map.set(company, []);
}
map.get(company).push(phone);
});
return map;
}