【问题标题】:Create and group new array from object and arrays从对象和数组创建和分组新数组
【发布时间】:2022-07-20 00:44:47
【问题描述】:

我有一个项目对象,每个键都是项目特征(颜色、尺寸或材料)的 ID。它们的值也是特征值(红色、蓝色等)的 ID。 我想将每个特征与其值分组(如在 resultArray 中)。我尝试使用 reduce 功能,但无法获得所需的结果。你能告诉我用什么方法来得到这个结果吗?

itemAttributes = { "11": [ 19,20 ], "12": [ 21, 22, 23], "13": [ 25, 26, 27 ]}

arr1 =[ 
  {title: "colors", "id": 11 }, 
  {title: "sizes", "id": 12 }, 
  {title: "materials", "id": 13 }
]

arr2=[ 
  {title: "red", "attribute": 11, id: 19 },
  {title: "blue", "attribute": 11, id: 20 }, 
  {title: "10x20", "attribute": 12, id: 21 }, 
  {title: "10x30", "attribute": 12, id: 22 },
  {title: "10x40", "attribute": 12, id: 23 },
  {title: "10x50", "attribute": 12, id: 24 },
  {title: "metals", "attribute": 13, id: 25 },
  {title: "polymers", "attribute": 13, id: 26 },
  {title: "ceramics", "attribute": 13, id: 27 },
]

resultArray = [
  {
    title: colors,
    items: [red, blue],
  },
  {
    title: sizes,
    items: [10x20, 10x30, 10x40],
  },
  {
    title: materials,
    items: [metals, polymers, ceramics],
  }]

【问题讨论】:

    标签: javascript arrays object reduce higher-order-functions


    【解决方案1】:

    我能想到的最短的是map 和内部filter+map。 由于是arr1的变换,所以可以使用map。在里面,我从arr2 过滤所需的项目,然后转换过滤后的项目以返回一个仅包含标题的数组

    let itemAttributes = { "11": [ 19,20 ], "12": [ 21, 22, 23], "13": [ 25, 26, 27 ]}
    
    let arr1 =[ 
      {title: "colors", "id": 11 }, 
      {title: "sizes", "id": 12 }, 
      {title: "materials", "id": 13 }
    ]
    
    let arr2=[ 
      {title: "red", "attribute": 11, id: 19 },
      {title: "blue", "attribute": 11, id: 20 }, 
      {title: "10x20", "attribute": 12, id: 21 }, 
      {title: "10x30", "attribute": 12, id: 22 },
      {title: "10x40", "attribute": 12, id: 23 },
      {title: "10x50", "attribute": 12, id: 24 },
      {title: "metals", "attribute": 13, id: 25 },
      {title: "polymers", "attribute": 13, id: 26 },
      {title: "ceramics", "attribute": 13, id: 27 },
    ]
    
    const res = arr1.map(({title,id}) => {
      const attrIds = itemAttributes[id]
      const items = arr2.filter(({id}) => attrIds.includes(id)).map(({title}) => title)
      return {title,items}
    })
    
    console.log(res)

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 2016-12-31
      • 2018-11-27
      • 1970-01-01
      • 2022-01-19
      • 2020-03-14
      • 1970-01-01
      • 2015-03-22
      相关资源
      最近更新 更多