反应重名但字段不同
React Duplicated Name but different fields
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" ]}
我将如何使用 React 来完成它?
这不是一个超级复杂的问题。您需要考虑如何使给定的输入数组值可迭代。
一旦你有了迭代的方法,应用你所要求的转换逻辑就会变得更容易,比如合并给定等级的域。
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);
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" ]}
我将如何使用 React 来完成它?
这不是一个超级复杂的问题。您需要考虑如何使给定的输入数组值可迭代。
一旦你有了迭代的方法,应用你所要求的转换逻辑就会变得更容易,比如合并给定等级的域。
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);