JavaScript-匹配ID的新对象数组

时间:2019-03-09 10:55:51

标签: javascript ecmascript-6

我只是想知道使用ES6在JavaScript中实现此目标的最佳方法。

使用以下数据:

categories: [
    {id: 1,name: "category 1",items: [19993, 99737]},
    {id: 2,name: "category 2",items: [70264, 65474, 07078]},
    {id: 3,name: "category 3",items: [76765]}
]

items: [
    {id: 19993, name: "item 1"},
    {id: 70264, name: "item 2"},
    {id: 99737, name: "item 3"},
    {id: 65474, name: "item 4"},
    {id: 76765, name: "item 5"},
    {id: 07078, name: "item 6"}
]

我正在尝试根据category.items数组中包含的ID为每个类别创建一个新的项目数组。

因此对于类别1,输出应为:

[
    {id: 19993, name: "item 1"},
    {id: 99737, name: "item 3"}
]

我知道我可以通过一堆循环来实现这一点,将其推入数组中,但是想知道是否存在一种较短的ES6方法来实现这一目标?

谢谢

4 个答案:

答案 0 :(得分:2)

id数组中按项目items创建一个Map。使用Array.map()迭代categories数组。对于每个类别,使用object spread创建一个新对象,然后从Map中填充items数组:

const categories = [{"id":1,"name":"category 1","items":[19993,99737]},{"id":2,"name":"category 2","items":[70264,65474,7078]},{"id":3,"name":"category 3","items":[76765]}]

const items = [{"id":19993,"name":"item 1"},{"id":70264,"name":"item 2"},{"id":99737,"name":"item 3"},{"id":65474,"name":"item 4"},{"id":76765,"name":"item 5"},{"id":7078,"name":"item 6"}]

const itemsMap = new Map(items.map(o => [o.id, o]))

const result = categories.map(o => ({
  ...o,
  items: o.items.map(id => itemsMap.get(id))
}))

console.log(result)

答案 1 :(得分:2)

您可以使用Array.prototype.map()Array.prototype.find()Array.prototype.filter()简洁地完成此操作:

const categories = [
    {id: 1,name: "category 1",items: [19993, 99737]},
    {id: 2,name: "category 2",items: [70264, 65474, 07078]},
    {id: 3,name: "category 3",items: [76765]}
];

const items = [
    {id: 19993, name: "item 1"},
    {id: 70264, name: "item 2"},
    {id: 99737, name: "item 3"},
    {id: 65474, name: "item 4"},
    {id: 76765, name: "item 5"},
    {id: 07078, name: "item 6"}
];

const result = categories.map(c => ({
    ...c,
    items: c.items.map(id => items.find(i => id === i.id)).filter(Boolean)
}));

console.log(result);

答案 2 :(得分:1)

您可以找到类别和项目。

select 'ScAnSection' AS `ScAnSection`,1 AS `ScAnAnswer1`,1 AS `ScAnBaselineFinal`
function getItemsByCategory(id) {
    var category = categories.find(o => o.id === id);
    if (category) {
        return category.items.map(id => items.find(o => o.id === id));
    }
}

var categories = [{ id: 1, name: "category 1", items: [19993, 99737] }, { id: 2, name: "category 2", items: [70264, 65474, 07078] }, { id: 3, name: "category 3", items: [76765] }],
    items = [{ id: 19993, name: "item 1" }, { id: 70264, name: "item 2" }, { id: 99737, name: "item 3" }, { id: 65474, name: "item 4" }, { id: 76765, name: "item 5" }, { id: 07078, name: "item 6" }];

console.log(getItemsByCategory(1));

答案 3 :(得分:1)

您可以使用reduceforEachfind

这里的想法是

  • 首先,对于类别中的每个项目数组,我们在.as-console-wrapper { max-height: 100% !important; top: 0; }变量中找到匹配的元素。
  • 如果找到匹配的元素,则将其添加到op中,否则不做任何更改就返回op

items