Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative option of for and findIndex Loop?

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);
like image 286
user88432 Avatar asked Jan 21 '26 03:01

user88432


1 Answers

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);
like image 181
Sandeep Acharya Avatar answered Jan 22 '26 15:01

Sandeep Acharya