gpt4 book ai didi

javascript - Javascript 中的转置

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:59 24 4
gpt4 key购买 nike

我有以下输入

[
{
"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 是否等于对象的属性名称,如果为真 .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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com