Problem:
heres a working example of what I’m trying to do:
private mergeData(dataArray) {
const mergedData = {
items: [],
money: {
money1: 0,
money2: 0,
money3: 0,
}
}
for (const data of dataArray) {
mergedData.money.money1 += data.money.money1
mergedData.money.money2 += data.money.money2
mergedData.money.money3 += data.money.money3
mergedData.items = [...mergedData.items, ...data.items]
}
return mergedData
}
I’m looking to optimize this as something about it feels smelly.
I have Lodash available in my project and would ideally use it if possible.
I would like to add more details as I seem to have posted this too hastily
dataArray looks like an array of these objects
{
items: [],
money: {
money1: 0,
money2: 0,
money3: 0,
}
}
And items is just an object with string key:value pairs
I’m looking to make this more concise and possibly optimize performance on item merging
Thanks.
Solution:
You can use reduce
private mergeData(dataArray) {
const mergedData = {
items: [],
money: {
money1: 0,
money2: 0,
money3: 0,
}
}
return dataArray.reduce((acc, curr) => {
acc.items.push(...curr.items)
acc.money.money1 += curr.money.money1
acc.money.money2 += curr.money.money2
acc.money.money3 += curr.money.money3
return acc;
}, mergedData)
}