My code:
export default {
data() {
return {
services: [],
mydata: [
{id: 1, count: 102, price: 0.1},
{id: 1, count: 0, price: 0.09},
{id: 2, count: 20, price: 0.5},
]
};
},
mounted() {
this.start();
},
methods: {
start() {
this.services = this.mydata.reduce((acc, curr) => {
let item = acc.find((obj) => obj.id == curr.id);
if (item) {
item.count += curr.count;
item.price = item.price > curr.price ? curr.price : item.price;
} else {
acc.push(curr);
}
return acc;
}, []);
},
},
};
I want merge the mydata array and save into a services variable. I want that the counts to be sum and the lower price to be selected for the new object. (I used reduce for doing this)
My expected services:
[
{id: 1, count: 102, price: 0.09},
{id: 2, count: 20, price: 0.5},
]
It's works but the source data (which is mydata) manipulated and converted to this: (the first object's price manipulated and converted to 0.09 which it was 0.1 before)
[
{id: 1, count: 102, price: 0.09},
{id: 1, count: 0, price: 0.09},
{id: 2, count: 20, price: 0.5}
]
Why does this happen?
mydata:JSON.parse(JSON.stringify(this.mydata)).reduce...