javascript - 修改 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'
}
]
};
请帮助我实现这一目标。提前致谢!
解决方案
您可以使用 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));
推荐阅读
- android - 使用颤振不停地振动
- php - 使用 laravel 理解模型关系
- javascript - 如何在 JS 中传递 C# 变量
- reactjs - 如何在输入和表单中使用循环?
- php - 未定义的属性:运行 laravel 项目的 stdClass::$column_name 问题
- wso2 - WSO2:使用 Integration Studio 的 RabbitMQ AMQP 传输消费者代理
- sql - Oracle加入递归
- javascript - 将输入事件应用于每个动态添加的文本输入
- mysql - Laraver 查询 Union All
- android - Flutter [错误:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:类型“int”不是类型转换中“String”类型的子类型