开发者社区> 问答> 正文

javascript按键拆分json对象

已解决

我有一种情况,我需要使用密钥分割后端给出的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"
        }
    ]
}

一定有天才能解决我的问题。非常感谢。欢迎任何建议。

展开
收起
sossssss 2019-11-28 17:34:21 1183 0
1 条回答
写回答
取消 提交回答
  • 采纳回答

    看进入并根据键的第一个字母对它们进行分组。如果组对象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 })
    
    2019-11-28 17:35:46
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript异步编程 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载