I am currently using for and findIndex to update the Totals in the main result variable. Is there an alternative way to rewrite this to be shorter or more readable?
const payload = [
{ Id: 1, Total: 5 },
{ Id: 3, Total: 2 },
]
const result = {
Items: [
{ Id: 1, Name: 'Item 1 A', Total: 1, Type: "Main"},
{ Id: 1, Name: 'Item 1 B', Total: 0},
{ Id: 2, Name: 'Item 2 C', Total: 1, Type: "Main"},
{ Id: 2, Name: 'Item 2 D', Total: 0},
{ Id: 3, Name: 'Item 3 E', Type: "Main"},
{ Id: 3, Name: 'Item 3 F', Total: 0},
]
}
for(const itemPayload of payload) {
const itemIndex = result.Items.findIndex(item => item.Id === itemPayload.Id && item.Type === "Main");
if (itemIndex !== -1) {
result.Items[itemIndex].Total = itemPayload.Total;
}
}
console.log(result);
Here we are creating a Map and then accessing it in a loop. It's much cleaner and more readable.
const payload = [
{ Id: 1, Total: 5 },
{ Id: 3, Total: 2 },
]
const result = {
Items: [
{ Id: 1, Name: 'Item 1 A', Total: 1, Type: "Main" },
{ Id: 1, Name: 'Item 1 B', Total: 0 },
{ Id: 2, Name: 'Item 2 C', Total: 1, Type: "Main" },
{ Id: 2, Name: 'Item 2 D', Total: 0 },
{ Id: 3, Name: 'Item 3 E', Type: "Main" },
{ Id: 3, Name: 'Item 3 F', Total: 0 },
]
};
const payloadMap = payload.reduce((map, obj) => {
map[obj.Id] = obj.Total;
return map;
}, {});
result.Items = result.Items.map(item => {
if (item.Type === 'Main' && payloadMap[item.Id]) {
item.Total = payloadMap[item.Id];
}
return item;
});
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With