首页 > 解决方案 > 使用 array.map 重新格式化对象数组

问题描述

我收到带有以下数组的 API 调用的结果,我正在尝试从以下位置重新格式化此数组:

const items = [
  {
    id: 1,
    name: "Item 1",
    section: { name: "Section A" }
  },
  {
    id: 2,
    name: "Item 2",
    section: { name: "Section A" }
  },
  {
    id: 3,
    name: "Item 3",
    section: { name: "Section A" }
  },
  {
    id: 4,
    name: "Item 4",
    section: { name: "Section B" }
  },
  {
    id: 5,
    name: "Item 5",
    section: { name: "Section B" }
  },
  {
    id: 6,
    name: "Item 6",
    section: { name: "Section C" }
  },
  {
    id: 7,
    name: "Item 7",
    section: { name: "Section C" }
  }
];

排列这个:

const items = [
      {
        section: "Section A",
        items: [
          {
            id: 1,
            item: "Item 1"
          },
          {
            id: 2,
            item: "Item 2"
          },
          {
            id: 3,
            item: "Item 3"
          }]
      },
      {
        section: "Section B",
        items: [
          {
            id: 4,
            item: "Item 4"
          },
          {
            id: 5,
            item: "Item 5"
          }]
      },
      {
        section: "Section C",
        items: [
          {
            id: 6,
            item: "Item 6"
          },
          {
            id: 7,
            item: "Item 7"
          }]
      },
    ]

我尝试了以下功能:

const result = Array.from(new Set(items.map(s => s.section.name)))
      .map(section => {
        return {
          section: section,
          items: Array.from(new Set(items.map(function (item) {
            if (item.section.name === section) {
              return item.name
            }
          }
          )))
        }
      })

这给了我以下结果,这很接近,但我不确定为什么我得到未定义的值?

//[{section: "Section A", items: ["Item 1", "Item 2", "Item 3", undefined]},{section: "Section B", items:[undefined, "Item 4", "Item 5"]},{section: "Section C", items: [undefined, "Item 6", "Item 7"]}]

任何人都可以帮助我更正此功能或提出更好的方法吗?

标签: javascriptarrays

解决方案


您可以使用一个对象进行分组并获取值作为结果。

const
    items = [{ id: 1, name: "Item 1", section: { name: "Section A" } }, { id: 2, name: "Item 2", section: { name: "Section A" } }, { id: 3, name: "Item 3", section: { name: "Section A" } }, { id: 4, name: "Item 4", section: { name: "Section B" } }, { id: 5, name: "Item 5", section: { name: "Section B" } }, { id: 6, name: "Item 6", section: { name: "Section C" } }, { id: 7, name: "Item 7", section: { name: "Section C" } }],
     result = Object.values(items.reduce((r, { section: { name: section }, ...item }) => {
        if (!r[section]) r[section] = { section, items: [] };
        r[section].items.push(item);
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读