I want to merge arrays of the same type. It comes from the database as follows.
const array =[
{
name: 'Iphone',
date: '01.01.2024',
img: 'img/iphone.png',
cost: 2500,
username:"Joe",
},
{
name: 'Samsung',
date: '01.01.2024',
img: 'img/samsung.png',
cost: 2000,
username:"Adam",
},
{
name: 'Samsung',
date: '01.01.2024',
img: 'img/samsung.png',
cost: 2000,
username:"Alvin",
}
]
I need to convert it to the following array?
const array =[
{
name: 'Iphone',
date: '01.01.2024',
img: 'img/iphone.png',
cost: 2500,
username:"Joe",
},
{
name: 'Samsung',
date: '01.01.2024',
img: 'img/samsung.png',
cost: 2000,
usernames:[{
username:"Adam"
},
{
username:"Alvin"
}]
,
},
]
Can you help me please?
4
Answers
First, get the unique phone names.
Then, for each name, find the matching phone entry, and extract all properties in to a new object. Then, add in all usernames for that phone name.
Finally, if there is more than one username, delete the username property for each object in the resulting array, so that there is only a usernames property at the top level. Otherwise, keep only the username property and delete the usernames property.
This code uses the reduce function to iterate through the initial array and create a new array (resultArray) in the desired format by checking if an object with the same ‘name’, ‘date’, ‘img’, and ‘cost’ already exists in the accumulator (acc). If it exists, it pushes the ‘username’ to the ‘usernames’ array. Otherwise, it creates a new object and initializes the ‘usernames’ array with the current ‘username’.
I suggest to use a simple array for the usernames. That accepted, a possible solution could look like this:
For performance, build a tree of property values with the leaves being object unique by all fields except
username
: