我有一种情况,我需要使用密钥分割后端给出的Json对象。下面是后端给出的JSON示例。
{
"answer": {
"E2": "Tony Stark",
"E3": "1",
"E4": "2",
"E6": "4",
"E8": "9120",
"E9": "01",
"F1": "Marvel",
"F2": "1",
"F4": "2",
"F6": "4",
"F8": "9120",
"F9": "01",
"G1": "02",
"G2": "02",
"G3": "02",
"H10": "Car"
}
}
我可以把答案分成E、F、G和H部分吗?预期结果是
{
"answer": [
{
"E2": "Tony Stark",
"E3": "1",
"E4": "2",
"E6": "4",
"E8": "9120",
"E9": "01",
"sectionName": "E"
},
{
"F1": "Marvel",
"F2": "1",
"F4": "2",
"F6": "4",
"F8": "9120",
"F9": "01",
"sectionName": "F"
},
{
"G1": "02",
"G2": "02",
"G3": "02",
"sectionName": "G"
},
{
"H10": "Car",
"sectionName": "H"
}
]
}
一定有天才能解决我的问题。非常感谢。欢迎任何建议。
看进入并根据键的第一个字母对它们进行分组。如果组对象alrady以字母为关键字,请更新它。否则,将字母作为键添加到组对象中。使用Object.values()获取的数组回答输出中需要的
const input={answer:{E2:"Tony Stark",E3:"1",E4:"2",E6:"4",E8:"9120",E9:"01",F1:"Marvel",F2:"1",F4:"2",F6:"4",F8:"9120",F9:"01",G1:"02",G2:"02",G3:"02",H10:"Car"}};
const group = {};
for (const [k, v] of Object.entries(input.answer)) {
const sectionName = k.charAt(0);
if (group[sectionName])
group[sectionName][k] = v;
else
group[sectionName] = { sectionName, [k]: v };
}
const answer = Object.values(group)
console.log({ answer })
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。