首页 > 解决方案 > 在另一个对象中获取对象属性的值(描述)

问题描述

我必须要通过 CategoryId 相互关联的对象数组。像下面的代码:

const Category = [
    { ID: 100 , Description: Cate1}, 
    {ID: 101 , Description: Cate2}
]
const Items = [ 
    {ID: 2001, CategoryID: 100, Desc: Item1 }, 
    {ID: 2002, CategoryID: 100, Desc: Item2 }, 
    {ID: 2003, CategoryID: 101, Desc: Item3 }, 
]

我将根据从两个数组中都存在的类别 id 中提取的类别描述,在 lis 中使用 map 方法来分配项目,这些项目在他们自己的 ul 中汇总。例如:

Cate1 > ul
  item1 > li
  item2 > li
Cate2 > ul
  item3 > li

. . . 如何使用 Javascript 或 ES6/7/8 解决这个问题?

标签: javascriptarraysmap-function

解决方案


您可以查看每个类别以及每个类别filter()的匹配项。这很容易,但是如果您有大量数据,则会有点慢,因为您每次都会遍历项目列表:

const Category = [{ ID: 100 , Description: 'Cate1'}, {ID: 101 , Description: 'Cate2'}]
const Items = [ {ID: 2001, 'CategoryID': 100, Desc: 'Item1' }, {ID: 2002, 'CategoryID': 100, Desc: 'Item2' }, {ID: 2003, 'CategoryID': 101, Desc: 'Item3' }, ]

Category.forEach(cat => {
    console.log('ul> '+cat.Description)
    Items.filter(item => item.CategoryID === cat.ID)
    .forEach(item => console.log('   li> ' + item.Desc))
})

或者,您可以根据 ID 为您的项目构建一个查找表,然后使用它在恒定时间内查找项目。对于更大的数据,这会更快,但需要更多的前期工作:

const Category = [{ ID: 100 , Description: 'Cate1'}, {ID: 101 , Description: 'Cate2'}]
const Items = [ {ID: 2001, 'CategoryID': 100, Desc: 'Item1' }, {ID: 2002, 'CategoryID': 100, Desc: 'Item2' }, {ID: 2003, 'CategoryID': 101, Desc: 'Item3' }, ]


let lookup = Items.reduce((a, c) => {
    (a[c.CategoryID] || (a[c.CategoryID] = [])).push(c)
    return a
}, {})

Category.forEach(cat => {
    console.log('ul> '+cat.Description)
    lookup[cat.ID]
    .forEach(item => console.log('   li> ' + item.Desc))
})


推荐阅读