首页 > 解决方案 > 修改 API 发送的 Javascript 对象

问题描述

我想修改 API 提供给客户端的数据。我只能使用 Set 检索唯一的类别值。然后我被卡住了如何进一步进行。

const serverData = [
    {
        category: 'address',
        label: 'Street',
        type: 'text'
    },
    {
        category: 'address',
        label: 'Country',
        type: 'text'
    },
    {
        category: 'person',
        label: 'FirstName',
        type: 'text'
    },
    {
        category: 'person',
        label: 'LastName',
        type: 'text'
    }
];

我希望将上面的内容修改如下。可以有很多类别

const modifiedData = {
    address : [
        {
            label: 'Street',
            type: 'text'
        },
        {
            label: 'Country',
            type: 'text'
        },
    ],
    person : [
        {
            label: 'FirstName',
            type: 'text'
        },
        {
            label: 'LastName',
            type: 'text'
        }
    ]
};

请帮助我实现这一目标。提前致谢!

标签: javascript

解决方案


您可以使用 reduce 函数来格式化数据。这是一个例子:

const serverData = [
  {
    category: 'address',
    label: 'Street',
    type: 'text'
  }, {
    category: 'address',
    label: 'Country',
    type: 'text'
  }, {
    category: 'person',
    label: 'FirstName',
    type: 'text'
  }, {
    category: 'person',
    label: 'LastName',
    type: 'text'
  }
];

const formatData = data => {
  return data.reduce((result, item) => ({
    ...result,
    [item.category] : [
      ...(result[item.category] || []),
      item
    ]
  }), {});
}

console.log(formatData(serverData));


推荐阅读