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.
3
Answers
You can use
reduce
You can optimize the merging of the array of objects using lodash’s _.mergeWith() function to merge the "money" properties and _.concat() to merge the "items" arrays. Here’s an example of how you can do it:
I would simplify the code using the following 2 points.
Reuse the
items
array instead of creating a new one each iteration. This can be done by pushingdata.items
into the existing array.Collect the money keys in a separate array before you start looping
dataArray
.Then add the values of the listed keys to the total for each
data.money
indataArray
.You can replace the
for...of
loop with something faster if you really need the additional speed.ps. If possible I would personally replace
{ money1: 0, money2: 0, money3: 0 }
with a simple array[0, 0, 0]
. As soon as you start numbering your attributes you probably want to use an array instead. This only works if you have control over the build process of the input structure.