【问题标题】:Use .find nested in .map to build array of objects使用嵌套在 .map 中的 .find 构建对象数组
【发布时间】:2018-09-13 08:47:39
【问题描述】:

我有 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 == 身份证

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

【问题讨论】:

  • filter 标签表明你知道你需要使用过滤器。您是否尝试过任何我们可以帮助您调试的方法?

标签: javascript arrays filter array.prototype.map


【解决方案1】:

由于the nature of Sets:以下解决方案比在Array.prototype.filter() 中嵌套Array.prototype.includes()time complex

请参阅和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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • .includes 的爱在哪里?使用.some 似乎有点矫枉过正。
    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 2015-10-18
    • 2017-07-02
    • 2021-10-04
    • 2022-01-08
    相关资源
    最近更新 更多