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

Use .find nested in .map to build array of objects

我有 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's

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

由于 the nature of Sets: the following solution is less time complex than nesting Array.prototype.includes() within Array.prototype.filter().

有关详细信息,请参阅 Set.has()

// Input.
const items = [{id: 1},{id: 5},{id: 12}]
const ids = [1, 4, 12]

// Filter.
const filter = (x, y) => {
  const s = new Set(y)
  return x.filter(({id}) => s.has(id))
}

// Output.
const output = filter(items, ids)

// Proof.
console.log(output)