3๐
โ
You can accomplish it by a single pass using js reduce()
so need need to use multiple loops.
const data = { colors: [{ "selectedColor": "white", "selectedQty": 0, "selectedUnit": "1", }, { "selectedColor": "black", "selectedQty": "2", "selectedUnit": "3", }, { "selectedColor": "black", "selectedQty": 5, "selectedUnit": "2", }, { "selectedColor": "red", "selectedQty": 0, "selectedUnit": "6", } ]};
const result = data.colors.reduce((acc, {
selectedColor: sc,
selectedQty: sq,
selectedUnit: su
}) => {
if (acc[sc]) return {
...acc,
[sc]: {
selectedColor: sc,
selectedQty: acc[sc].selectedQty + parseInt(sq),
selectedUnit: acc[sc].selectedUnit + parseInt(su)
}
}
return {
...acc,
[sc]: {
selectedColor: sc,
selectedQty: parseInt(sq),
selectedUnit: parseInt(su)
}
}
}, {});
console.log(Object.values(result));
๐คAsraf
2๐
You should create a computed method to create a new array, Instead of calling the data in your v-for
you can call the computed.
I did that in a codepen :
https://codepen.io/ValentinM27/pen/GRGvmMp?editors=1011
Here is the main part of the code :
...
computed: {
getGrouped() {
let groupedColor = [];
this.colors.forEach((c, index) => {
// We check if the color has already been handle
const alreadyExist = groupedColor.some(existC => existC.selectedColor === c.selectedColor);
// If yes, we don't handle it again
if(alreadyExist) return;
this.colors.forEach((c2, index2) => {
// If it is the same color but not the actual index, we do the traitement
if(c.selectedColor === c2.selectedColor && index !== index2) {
c.selectedQty = parseInt(c.selectedQty) + parseInt(c2.selectedQty);
c.selectedUnit = parseInt(c.selectedUnit) + parseInt(c2.selectedUnit);
}
})
// We push the concatened color value
groupedColor.push(c);
})
// Our array with concatened values
return groupedColor;
}
},
...
And in your template
...
<tbody v-for="(color, i) in getGrouped" :key="i">
...
Hope it is what you are looking for
Source:stackexchange.com