Javascript reduce,返回对象数组而不是对象[重复]

jaql4c8m  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(164)
    • 此问题在此处已有答案**:

Javascript - group array of objects by common values with label(5个答案)
昨天关门了。
我有以下reduce函数,它按类别对用户指南对象数组进行分组:

const groupByCategory = newUserGuides.reduce((group, userGuide) => {
  const { category } = userGuide;
  group[category] = group[category] ?? [];
  group[category].push(userGuide);
  return group;
}, {});

下面是我的原始数组:

[
    {
        category: "Data",
        description: "user guide 1",
        name: "User Guide 1"
    },
    {
        category: "Data",
        description: "user guide 2",
        name: "User Guide 2"
    },
    {
        category: "Pupils",
        description: "user guide 3",
        name: "User Guide 3"
    }
]

但是,它将以如下方式返回:

{
    Data: (3) [{…}, {…}, {…}],
    Pupils: (3) [{…}, {…}, {…}]
}

有没有办法像对象数组一样返回它:

[
    {category: 'Data', user_guides: [{...}]},
    {category: 'Pupils', user_guides: [{...}]}
]
to94eoyn

to94eoyn1#

数组可以直接由.reduce()生成,但回调变得复杂,因为它需要标识要更新的数组的正确项。
让它保持原样,然后处理groupByCategory的条目以获得预期结果:

const list = Object.entries(groupByCategory).map(
  ([key, value]) => ({ category: key, user_guides: value })
);

查看实际应用:

const newUserGuides = [
  {
    category: "Data",
    description: "user guide 1",
    name: "User Guide 1",
  },
  {
    category: "Data",
    description: "user guide 2",
    name: "User Guide 2",
  },
  {
    category: "Pupils",
    description: "user guide 3",
    name: "User Guide 3",
  },
];

const groupByCategory = newUserGuides.reduce((group, userGuide) => {
  const { category } = userGuide;
  group[category] = group[category] ?? [];
  group[category].push(userGuide);
  return group;
}, {});

const list = Object.entries(groupByCategory).map(
  ([key, value]) => ({ category: key, user_guides: value })
);
console.log(list);

了解Object.entries()

bis0qfac

bis0qfac2#

const source = [{
    category: "Data",
    description: "user guide 1",
    name: "User Guide 1",
  },
  {
    category: "Data",
    description: "user guide 2",
    name: "User Guide 2",
  },
  {
    category: "Pupils",
    description: "user guide 3",
    name: "User Guide 3",
  }
]

// DESIRED OUTPUT
// [{category: 'Data', user_guides: [{...}]},
// {category: 'Pupils', user_guides: [{...}]}]

const newData = source.reduce((arr, item) => {
  const data = arr.find(i => i.category === item.category) || { category: item.category, user_guides: []}
  
  data.user_guides.push({ description: item.description, name: item.name })
  arr.push(data);

  return arr;
}, [])

console.log(newData)

相关问题