I have an array of objects in the format below and would like to transform it into a new array of objects using a property as a key. The key should be unique. See shape of the object below
const mockedList = [
{
email: 'aaa@example.com',
id: '5052',
name: 'Java',
},
{
email: 'bbb@example.com',
id: '5053',
name: 'Python',
},
{
email: 'aaa@example.com',
id: '5054',
name: 'C#',
},
{
email: 'bbb@example.com',
id: '5055',
name: 'Javascript',
},
];
I would like to transform this and get an array of objects with keys and values in this format.
[
{
email: 'bbb@example.com',
languages: [
{
email: 'bbb@example.com',
id: '5055',
name: 'Javascript',
},
{
email: 'bbb@example.com',
id: '5053',
name: 'Python',
},
]
},
{
email: 'aaa@example.com',
languages: [
{
email: 'aaa@example.com',
id: '5052',
name: 'Java',
},
{
email: 'aaa@example.com',
id: '5054',
name: 'C#',
},
]
}
]
I’ve tried using map-reduce
const result = mockedList.reduce((r, a) => {
r[a.email] = r[a.email] || [];
r[a.email].push(a);
return r;
}, Object.create(null));
But did not get the right shape of data
>Solution :
You can do:
const mockedList = [{email: 'aaa@example.com',id: '5052',name: 'Java',},{email: 'bbb@example.com',id: '5053',name: 'Python',},{email: 'aaa@example.com',id: '5054',name: 'C#',},{ email: 'bbb@example.com', id: '5055', name: 'Javascript' },]
const mockedListHash = mockedList.reduce((a, c) => {
a[c.email] = a[c.email] || { email: c.email, languages: [] }
a[c.email].languages.push(c)
return a
}, {})
const result = Object.values(mockedListHash)
console.log(result)
In case you want to clean the repeated emails within languages:
const mockedList = [{email: 'aaa@example.com',id: '5052',name: 'Java',},{email: 'bbb@example.com',id: '5053',name: 'Python',},{email: 'aaa@example.com',id: '5054',name: 'C#',},{ email: 'bbb@example.com', id: '5055', name: 'Javascript' },]
const mockedListHash = mockedList.reduce((a, c) => {
a[c.email] = a[c.email] || { email: c.email, languages: [] }
a[c.email].languages.push({
id: c.id,
name: c.name,
})
return a
}, {})
const result = Object.values(mockedListHash)
console.log(result)