简体   繁体   English

在另一个对象中获取对象属性的值(描述)

[英]Getting Value (Description) of an object's property in another object

I have to array of objects which can be related to each other through CategoryId. 我必须排列可以通过CategoryId相互关联的对象数组。 like below code: 像下面的代码:

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 }, 
]

I am going to distribute items by the use of map method in lis that are summarized in their own ul according to the category descriptions that are extracted from category id which exists in both arrays. 我将使用lis中的map方法来分发项目,这些方法根据从两个数组中都存在的类别ID中提取的类别描述在其自己的ul中进行了总结。 For example: 例如:

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

. . . How can I tackle this issue with Javascript or ES6/7/8? 如何使用Javascript或ES6 / 7/8解决此问题?

You can look at each category and for each one filter() the matching items. 您可以查看每个类别,并针对每个filter()匹配项。 This is easy, but will be a little slow if you have lots of data because you loop though the item list every time: 这很容易,但是如果您有很多数据,将会有点慢,因为每次都循环浏览项目列表:

 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)) }) 

Alternatively you can build a lookup table for your items base on ID once, and then use it to find the items in constant time. 或者,您可以一次基于ID为您的商品建立一个查找表,然后用它在恒定时间内查找商品。 This will be faster with larger data, but requires a little more work upfront: 使用更大的数据,这将更快,但需要做更多的事:

 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)) }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM