javascript - 在另一个对象中获取对象属性的值(描述)
问题描述
我必须要通过 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 解决这个问题?
解决方案
您可以查看每个类别以及每个类别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))
})
推荐阅读
- sql-server - 标记应在触发前或触发后使用
- python - 平均定义 - Python
- reactjs - 如何更改 StoryBook 上的画布背景颜色?
- amazon-web-services - 在 aws -terraform 中使用凭证获取 accountid:getcalleridentity 时出错
- spring-boot - Spring 资源加载在“特定”上下文路径上失败
- java - 解释 Java 代码实际上是什么意思?
- php - 忽略setter注入中缺少的方法
- ios - 我的键盘读取 SMS OTP 的正确格式是什么?iOS
- python - 如何在 Python 列表中查找特定模式?
- pyspark - 通过pyspark向kudu写入数据