【问题标题】:reduce nested dictionary of depth 2减少深度为 2 的嵌套字典
【发布时间】:2020-06-07 09:33:29
【问题描述】:

我有一个数据结构:

 {"nodes": [
        {
            "NLPTag": {
                "value": "Pope",
                "pos": "PROPN",
                "index": 2,
                "uuid": "26acad7d-799b-4de2-9bfa-f0330aee4d79",
                "id": 816753
            }, .... ]}

其中有一个字典列表。该字典的键具有类型。 我想要的输出是:

 {"nodes": [
        {"type":"NLPTag",
         "value": "Pope",
         "pos": "PROPN",
         "index": 2,
         "uuid": 816753
            }, .... ]}

为此我已经尝试过:

data.nodes.map(function(node) {

        const type = Object.keys(node)[0];

        node[type]["type"] = type; 
        node[type]["id"] = node[type]["uuid"];
        delete node[type]["uuid"];

        return node[type] 

    }) 

但这会导致数据结构与示例一中的嵌套类似。深度 2 的字典发生了变化,但我没有删除嵌套:

data = {"nodes":[
          {"NLPTag": {
                "type":"NLPTag",
                "id":"26acad7d-799b-4de2-9bfa-f0330aee4d79"...
                     }
           },....]}

谁能帮忙告诉我哪里出错了?

【问题讨论】:

    标签: javascript arrays dictionary foreach


    【解决方案1】:

    你可以使用对象解构:

    const result = {nodes: data.nodes.map(item => ({...Object.values(item)[0] }))}
    

    演示:

    const data = {
        "nodes": [
            {
                "NLPTag": {
                    "value": "Pope",
                    "pos": "PROPN",
                    "index": 2,
                    "uuid": "26acad7d-799b-4de2-9bfa-f0330aee4d79",
                    "id": 816753
                }, 
            },
            {
                "foo": {
                    "value": "foo",
                    "pos": "foo",
                    "index": 2,
                    "uuid": "foo",
                    "id": 45654
                }, 
            }
        ]
    }
    
    
    const result = {nodes: data.nodes.map(item => ({...Object.values(item)[0] }))}
    
    console.log(result);
    
    // {
    //     "nodes": [
    //         {
    //             "value": "Pope",
    //             "pos": "PROPN",
    //             "index": 2,
    //             "uuid": "26acad7d-799b-4de2-9bfa-f0330aee4d79",
    //             "id": 816753
    //         },
    //         {
    //             "value": "foo",
    //             "pos": "foo",
    //             "index": 2,
    //             "uuid": "foo",
    //             "id": 45654
    //         }
    //     ]
    // }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多