gpt4 book ai didi

javascript - for 和 findIndex 循环的替代选项?

转载 作者:行者123 更新时间:2023-12-01 11:12:02 24 4
gpt4 key购买 nike

我目前正在使用 forfindIndex 来更新主 result 变量中的总计。是否有其他方法可以将其重写为更短或更易读?

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);

最佳答案

这里我们创建了一个Map,然后循环访问它。它更清晰,更具可读性。

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);

关于javascript - for 和 findIndex 循环的替代选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59020315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com