this is how the object look:
let data = [ { brandId: '12345', brand: 'Adidas', item: { name: 'Adidas 1', price: '200', }, }, { brandId: '12345', brand: 'Adidas', item: { name: 'Adidas 2', price: '230', }, }, { brandId: '7878', brand: 'Nike', item: { name: 'Nike 1', price: '305', }, } ];
i want the item
object will merge if the object have the same brandID
:
let data = [ { brandId: '12345', brand: 'Adidas', item: [ { name: 'Adidas 1', price: '200', }, { name: 'Adidas 2', price: '230', }, ], }, { brandId: '7878', brand: 'Nike', item: { name: 'Nike 2', price: '316', }, }, ];
is there any javascript syntax or method to do this? and with an explanation will be very nice, Thank You
(Assuming that your output is just a typo and name/price doesn't actually changes) You can use array reduce
let data = [
{
brandId: '12345',
brand: 'Adidas',
item: {
name: 'Adidas 1',
price: '200',
},
},
{
brandId: '12345',
brand: 'Adidas',
item: {
name: 'Adidas 2',
price: '230',
},
},
{
brandId: '7878',
brand: 'Nike',
item: {
name: 'Nike 1',
price: '305',
},
}
];
const mergedItems = data.reduce((acc, curr) => {
// check if current exist on the accumulator
const exist = acc.find(brand => brand.brandId === curr.brandId);
// if it does, add the item on it
if (exist) {
return acc.map((brand) => {
if (brand.brandId === exist.brandId) {
return {
...brand,
item: brand.item.concat(curr.item),
}
}
})
}
// if it doesnt, add it on accumulator, and make the item array
return acc.concat({
...curr,
item: [
curr.item
]
})
})
(I wrote the code manually and not tested)
You can simply achieve this result using Map
let data = [ { brandId: "12345", brand: "Adidas", item: { name: "Adidas 1", price: "200", }, }, { brandId: "12345", brand: "Adidas", item: { name: "Adidas 2", price: "230", }, }, { brandId: "7878", brand: "Nike", item: { name: "Nike 1", price: "305", }, }, ]; const dict = new Map(); data.forEach((o) => { dict.get(o.brandId)? dict.get(o.brandId).item.push(o.item): dict.set(o.brandId, {...o, item: [o.item] }); }); const result = []; for (let [k, v] of dict) { v.item.length === 1? result.push({...v, item: v.item[0] }): result.push(v); } console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */.as-console-wrapper { max-height: 100%;important: top; 0; }
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.