代码之家  ›  专栏  ›  技术社区  ›  Polygon Pusher

从具有ids javascript数组的对象数组中选择对象

  •  1
  • Polygon Pusher  · 技术社区  · 7 年前

    假设我有一个这样的对象列表。

    const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}]
    

    然后我有一个清单,我想在上面的清单中找到。

    const ids = [1, 3]
    

    如何返回与中找到的ID匹配的对象数组 ids list 使用javascript?

    这是一个例子,我想看到的回报给我给定的[1,3]。

    -> [{id: 1, name: "foo"}, {id: 3, name: "baz"}]
    

    谢谢 -乔希

    2 回复  |  直到 7 年前
        1
  •  4
  •   P.S.    7 年前

    你可以通过 filter 方法,该方法根据您在其中编写的条件返回新的项数组。我也推荐使用 includes 方法检查您的ID数组是否具有以下项:

    const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}];
    const ids = [1, 3];
    const newArr = list.filter(item => ids.includes(item.id));
    console.log(newArr);
        2
  •  0
  •   Kosh    7 年前

    你可以用它 map find 以下内容:

    const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}];
    const ids = [1, 3];
    const newArr = ids.map(i => list.find(({id}) => i === id));
    console.log(newArr);