我有以下输入
[
{
"level1": [
{ "subject": "English", "avgScore": 100% },
{ "subject": "Math", "avgScore": 80% }
]
},
{
"level2": [
{ "subject": "English", "avgScore": 90% },
{ "subject": "Math", "avgScore": 75% }
]
},
{
"level3": [
{ "subject": "English", "avgScore": 100% },
{ "subject": "Math", "avgScore": 80% },
{ "subject": "Science", "avgScore": 90% }
]
},
{
"level4": [
{ "subject": "Math", "avgScore": 80% },
{ "subject": "Science", "avgScore": 90% }
]
},
{
"level5": [
{ "subject": "Computer", "avgScore": 80% }
]
}
]
我试着转换成下面的形式
[
{
label: "English",
values:[
{ grade: "level1", avgScore: 100% },
{ grade: "level2", avgScore: 90% },
{ grade: "level3", avgScore: 100% }
]
},
{
label: "Math",
values:[
{ grade: "level1", avgScore: 80% },
{ grade: "level2", avgScore: 75% },
{ grade: "level3", avgScore: 80% },
{ grade: "level4", avgScore: 80% }
]
},
{
label: "Science",
values:[
{ grade: "level3", avgScore: 90% },
{ grade: "level4", avgScore: 90% }
]
},
{
label: "Computer",
values:[
{ grade: "level5", avgScore: 80% }
]
}
]
到目前为止,我有以下代码没有给出数组值
convert( inputFormat) {
const subjects = Array.from( inputFormat.reduce((acc, subject) => {
const level = Object.keys(subject)[0];
subject[level].forEach((levelZone) => {
acc.add(levelZone.subject);
});
return acc;
}, new Set()));
return subjects.map((subject) => {
return {
label: subject,
values: inputFormat.map((subject) => {
return Object.keys(subject)[0]
}, []);
}
});
}
最佳答案
您可以在.map()
中迭代输入数组,以检查subject
是否等于对象的属性名,如果为true.push()
"avgScore"
值,并且在"grade"
处设置的属性名是否等于属性名。
const input = [{
"level1": [{
"subject": "English",
"avgScore": "100%"
},
{
"subject": "Math",
"avgScore": "80%"
}
]
},
{
"level2": [{
"subject": "English",
"avgScore": "90%"
},
{
"subject": "Math",
"avgScore": "75%"
}
]
},
{
"level3": [{
"subject": "English",
"avgScore": "100%"
},
{
"subject": "Math",
"avgScore": "80%"
},
{
"subject": "Science",
"avgScore": "90%"
}
]
},
{
"level4": [{
"subject": "Math",
"avgScore": "80%"
},
{
"subject": "Science",
"avgScore": "90%"
}
]
},
{
"level5": [{
"subject": "Computer",
"avgScore": "80%"
}]
}
];
function convert(inputFormat) {
return Array.from(
[...new Set(
inputFormat.map(prop => {
const [{subject}] = prop[Object.keys(prop).pop()];
return subject
})
)
]
, label => {
const values = [];
for (const prop of inputFormat) {
for (const [grade, props] of Object.entries(prop)) {
for (const {subject, avgScore} of props) {
label === subject && values.push({avgScore, grade})
}
}
}
return {label, values}
})
}
console.log(convert(input));
关于javascript - 用Javascript转置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46614942/