gpt4 book ai didi

javascript - 减少循环逻辑?

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:17 24 4
gpt4 key购买 nike

有没有办法重构它,使代码看起来更短、更易读? payload 中的 Id 不会超过 100 个,因此我认为在这种情况下性能并不重要。

const payload = {
RequestIds: [
{ Id: 1 },
{ Id: 3 },
]
}

const result = {
Items: [
{ Id: 1, Name: 'Item 1 A'},
{ Id: 1, Name: 'Item 1 B'},
{ Id: 2, Name: 'Item 2 C'},
{ Id: 2, Name: 'Item 2 D'},
{ Id: 3, Name: 'Item 3 E'},
{ Id: 3, Name: 'Item 3 F'},
]
}


const items = [];
for(const payloadItem of payload.RequestIds) {
const filteredItems = result.Items.filter(item => item.Id === payloadItem.Id);

if (filteredItems.length > 0) {
items.push(...filteredItems);
}
}

console.log(items);

最佳答案

在有效负载中创建一组 Id,然后根据是否包含正在迭代的 Id 执行单个 .filter:

const payload = {
RequestIds: [
{ Id: 1 },
{ Id: 3 },
]
};
const payloadIds = new Set(payload.RequestIds.map(({ Id }) => Id));

const result = {
Items: [
{ Id: 1, Name: 'Item 1 A'},
{ Id: 1, Name: 'Item 1 B'},
{ Id: 2, Name: 'Item 2 C'},
{ Id: 2, Name: 'Item 2 D'},
{ Id: 3, Name: 'Item 3 E'},
{ Id: 3, Name: 'Item 3 F'},
]
}

const items = result.Items.filter(({ Id }) => payloadIds.has(Id));
console.log(items);

关于javascript - 减少循环逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59017937/

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