json - 反应重复名称但不同的字段
问题描述
React 应用程序我从 react-select 的 API 部分获取 JSON 数据:
import Select from "react-select";
import fetch from "isomorphic-fetch";
return fetch(`some API localhost`)
.then(response => response.json())
.then(json => {
return { options: json };
})
现在选项如下所示:
{"Grade": "Math K", "Domain": "Counting & Cardinality"},
{"Grade": "Math K", "Domain": "Geometry"},
{"Grade": "Math 1", "Domain": "Counting & Cardinality"},
{"Grade": "Math 1", "Domain": "Orders of Operation"},
{"Grade": "Math 1", "Domain": "Geometry"},
我想合并重复的成绩并使其类似于:
{"Grade": "Math K", "Domain": ["Counting & Cardinality", "Geometry"]},
{"Grade": "Math 1", "Domain": ["Counting & Cardinality" , "Geometry" , "Orders of Operation" ]}
我将如何使用反应来做到这一点?
解决方案
这不是一个超级复杂的问题。您需要考虑如何使给定的输入数组值可迭代。
一旦你有了迭代的方法,应用你所要求的转换逻辑就变得更容易了,比如合并给定等级的域。
const response = [{
"Grade": "Math K",
"Domain": "Counting & Cardinality"
},
{
"Grade": "Math K",
"Domain": "Geometry"
},
{
"Grade": "Math 1",
"Domain": "Counting & Cardinality"
},
{
"Grade": "Math 1",
"Domain": "Orders of Operation"
},
{
"Grade": "Math 1",
"Domain": "Geometry"
}
];
const output = {};
response.forEach((item) => {
const grade = item.Grade;
// Create a Map / Object to access a particular Grade easily
output[grade] = output[grade] || {};
output[grade].Grade = grade;
output[grade].Domain = output[grade].Domain || [];
output[grade].Domain.push(item.Domain);
})
const outputObj = Object.keys(output).map((item) => output[item]);
console.log(outputObj);
推荐阅读
- java - 与多线程服务器的繁忙循环相比,Java 互斥体导致输入丢失?
- properties - 如何从属性设置器更改对象属性的子属性,以便能够(重新)设置对象?
- git - 重新规范化 repo 的整个历史记录,而不以任何其他方式创建新的提交/更改历史记录
- proxy - 为什么当我通过 Jmeter 代理执行搜索事务时应用程序会抛出错误,但当我手动执行事务时不会?
- python - Discord Bot 离开前未播放 mp3 文件
- python - 将数据框的字典写入excel文件会产生错误
- python - 计算精度(在 lstm 模型中)
- .net - Sendgrid SendEmailAsync 响应内容始终为空
- python - sklearn FeatureHasher 输出有很多冲突和未使用的列
- javascript - VSCODE 在尝试调试 javascript 时出错:“vscode listen eacces: permission denied 127.0.0.1:53942”