I am struggling to generate a new array of objects from one that contains duplicates. For instance, here is the console.log output of the current array:
console.log(items);
[{
_id: 5eb2f7efb5b8fa62bcd7db94,
workName: 'best item ever',
workTitle: 'this is the description',
price: 300,
},
<Three objects with this id: 5eb2f7efb5b8fa62bcd7db94>
{
_id: 5eb19f3bad682508dc024301,
workName: 'pack your gift',
workTitle: 'best packaging for your gift',
price: 5,
},
{
<Two objects with this id: 5eb19f3bad682508dc024301>
}]
Is there a way to count the objects, calculate the total price and obtain an array of objects like the following example?
[{
_id: 5eb2f7efb5b8fa62bcd7db94,
workName: 'best item ever',
workTitle: 'this is the description',
price: 300,
quantity: 3,
totalPrice: 900
},
{
_id: 5eb19f3bad682508dc024301,
workName: 'pack your gift',
workTitle: 'best packaging for your gift',
price: 5,
quantity: 2,
totalPrice: 10
}]
Although I've attempted some solutions, I'm unable to figure out how to create the specified new array.
<all variables declaration>
if (cookies) {
for (let key in cookies) {
// create new array with works obj
items.push(value.work = await Work.findById({ _id: cookies[key] }));
// convert cookies object into an array with the values
id.push(cookies[key]);
}
// return an object where the key is the input array and the value is the number of duplicates
id.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
let counter = 0;
for (let i in counts) {
counter += 1;
totalPartial.push(items[counter].price * counts[i]);
};
}
//swapping objects
const newData = Object.keys(counts).reduce(async (obj, key) => {
obj[counts[key]] = key;
return obj;
}, {});
const total = totalPartial.reduce((partial_sum, a) => partial_sum + a, 0);