I have this data where it repeats the items that were placed. How can I group the data according to their id and add an array of variations that will store the various colors and their quantity?
This is the current sample data that I have:
const data = [
{
id: "aRLMZkiSU7T0lcsPCSsV",
name: "Tumbler",
price: 200,
size: "500",
cat: "ML",
color: "Green",
quantity: 2
},
{
id: "aRLMZkiSU7T0lcsPCSsV",
name: "Tumbler",
price: 200,
size: "500",
cat: "ML",
color: "Pink",
quantity: 1
},
{
id: "aRLMZkiSU7T0lcsPCSsV",
name: "Tumbler",
price: 200,
size: "500",
cat: "ML",
color: "Black",
quantity: 11
},
{
id: "y9ECyZBKp2OBekmWym4M",
name: "Notebook",
price: 250,
size: "200",
cat: "CM",
color: "Red",
quantity: 1
},
{
id: "y9ECyZBKp2OBekmWym4M",
name: "Notebook",
price: 250,
size: "200",
cat: "CM",
color: "Green",
quantity: 4
}
];
I just want to know how I could destructure this data to something like this where the duplicated id will be group and then the color and quantity will be pushed inside the variations array:
id: "aRLMZkiSU7T0lcsPCSsV",
name: "Tumbler",
price: 200,
size: "500",
cat: "ML",
variations: [
{name: "Green", quantity: 1},
{name: "Black", quantity: 10},
]
From what I have done, I have merged it already except for the part for the variations array. How can I create the variations array ?
codesandbox: https://codesandbox.io/s/data-restructure-u2ss8z?file=/src/App.js
const mapById = data.reduce(
(acc, { id, name, size, cat, price, color, quantity }) => {
acc[id] = {
id,
name,
size,
cat,
price,
color,
quantity
};
return acc;
},
{}
);
>Solution :
Initially you have to check if an object with id key is present, if not create it with an empty variations array. then added to the variations array based on the current id
const data = [
{
id: "aRLMZkiSU7T0lcsPCSsV",
name: "Tumbler",
price: 200,
size: "500",
cat: "ML",
color: "Green",
quantity: 2
},
{
id: "aRLMZkiSU7T0lcsPCSsV",
name: "Tumbler",
price: 200,
size: "500",
cat: "ML",
color: "Pink",
quantity: 1
},
{
id: "aRLMZkiSU7T0lcsPCSsV",
name: "Tumbler",
price: 200,
size: "500",
cat: "ML",
color: "Black",
quantity: 11
},
{
id: "y9ECyZBKp2OBekmWym4M",
name: "Notebook",
price: 250,
size: "200",
cat: "CM",
color: "Red",
quantity: 1
},
{
id: "y9ECyZBKp2OBekmWym4M",
name: "Notebook",
price: 250,
size: "200",
cat: "CM",
color: "Green",
quantity: 4
}
];
const mapById = data.reduce(
(acc, { id, name, size, cat, price, color, quantity }) => {
if(!acc[id])acc[id] = {id,name,size,cat,price,variations:[]}
acc[id].variations.push({name:color, quantity})
return acc;
},
{}
);
console.log(mapById)