我只是想知道使用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方法来实现这一目标?
谢谢
答案 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)