创建多个对象的新数组以及从给定数组创建数组

问题描述 投票:0回答:1

我有以下数组

const CARS = 
[
  {make: "skoda", model: "kodiaq", color: "light-blue", id: "1002", category: "A"},
  {make: "skoda", model: "karoq", color: "green", id: "1008", category: "B"},
  {make: "renault", model: "clio", color: "grey", id: "1006", category: "A"},
  {make: "renault", model: "kangoo", color: "white", id: "1042", category: "C"},
  {make: "mazda", model: "cx3", color: "red", id: "1022", category: "C"},
  {make: "mazda", model: "cx30", color: "orange", id: "1106", category: "D"},
  {make: "ford", model: "explorer", color: "grey", id: "1162", category: "B"},
  {make: "ford", model: "edge", color: "red", id: "1862", category: "A"}
]

我需要创建一个新的对象数组,按“类别”属性分组,如下所示


const NEW_CARS = 
[
  {
    category: "A",
    data: 
     [
       {make: "skoda", model: "kodiaq", color: "light-blue", id: "1002", category: "A"},
       {make: "renault", model: "clio", color: "grey", id: "1006", category: "A"},
       {make: "ford", model: "edge", color: "red", id: "1862", category: "A"}
     ]
  },
  {
    category: "B",
    data: 
     [
       {make: "skoda", model: "karoq", color: "green", id: "1008", category: "B"},
       {make: "ford", model: "explorer", color: "grey", id: "1162", category: "B"},
     ]
  },
  {
    category: "C",
    data: 
     [
       {make: "renault", model: "kangoo", color: "white", id: "1042", category: "C"},
       {make: "mazda", model: "cx3", color: "red", id: "1022", category: "C"}
     ]
  },

  {
    category: "D",
    data: 
     [
       {make: "mazda", model: "cx30", color: "orange", id: "1106", category: "D"}
     ]
  }
]

我想我需要从原始数组中提取类别列表,然后再次循环创建一个新数组。我迷路了,也不确定什么是最高效的方法,因为我的数组实际上相当大。

javascript arrays reduce array-map
1个回答
0
投票

您可以使用

Object.groupBy
然后转换为您想要的形式:

Object.entries(
  Object.groupBy(CARS, ({ category }) => category)
).map(([category, data]) => ({ category, data }))
© www.soinside.com 2019 - 2024. All rights reserved.