gpt4 book ai didi

javascript - 使用 .find 嵌套在 .map 中构建对象数组

转载 作者:行者123 更新时间:2023-11-29 18:55:28 25 4
gpt4 key购买 nike

我有 2 个数组。

1) ID 数组。前任。 item_ids: [1, 4, 12]

2) 对象数组

例如。

items: [
0: {id: 1...},
1: {id: 5...},
2: {id: 12...}
]

我需要构建一个新数组,其中包含来自第二个数组的对象,items,其 ID 在第一个数组中找到。

在这种情况下,它将是一个由对象 1 和 3 组成的数组,因为它们的 ID 存在于第一个数组中

这是我目前正在尝试的,但它为所有三个对象返回 undefined(我在使用它的示例中有 3 个)

let new_avails = avails.avails_to_update.map(id => {
this.state.availabilities.availabilities.find(function(a) {
return a.id == id
})
}, this)

avails_to_update == id 的

this.state.availabilities.availabilities == 对象数组

最佳答案

函数 map 将创建一个与原始数组长度相同的新数组。

使用函数 filter 和函数 includes 来完成您的要求。

var item_ids= [1, 4, 12],
items= [{id: 1},{id: 5},{id: 12}],
filtered = items.filter(item => (item_ids.includes(item.id)));

console.log(filtered)
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 使用 .find 嵌套在 .map 中构建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640010/

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