代码之家  ›  专栏  ›  技术社区  ›  bluprince13

从JSON提取键值数组

  •  0
  • bluprince13  · 技术社区  · 8 年前

    如何从嵌套的JS对象生成某个键值对的数组?有没有一个lodash函数来做这种事情?

    原始数据

    {
      "data": {
        "allLecturesJson": {
          "edges": [
            {
              "node": {
                "index": 1,
                "date": "01/02/2018",
                "presenter": "Mary",
              }
            },
            {
              "node": {
                "index": 2,
                "date": "01/03/2018",
                "presenter": "Jack",
              }
            },
      }
    }
    

    预期结果

    [
      {
        "index": 1,
        "date": "01/02/2018",
        "presenter": "Mary",
      },
      {
        "index": 2,
        "date": "01/03/2018",
        "presenter": "Jack"
      }
    ]
    
    4 回复  |  直到 8 年前
        1
  •  4
  •   Strelok    8 年前
    jsonData.data.allLecturesJson.edges.map(e => e.node)
    

        2
  •  2
  •   Mamun    8 年前

    map()

    Array.prototype.map()

    var jsonData = {
      "data": {
        "allLecturesJson": {
          "edges": [
            {
              "node": {
                "index": 1,
                "date": "01/02/2018",
                "presenter": "Mary",
              }
            },
            {
              "node": {
                "index": 2,
                "date": "01/03/2018",
                "presenter": "Jack",
              }
            }
          ]
        }
      }
    }
    
    var resArr = jsonData.data.allLecturesJson.edges.map(i => i.node);
    console.log(resArr);
        3
  •  0
  •   Rahul Gaba    8 年前

    Array.prototype.reduce()

    const input = {
      "data": {
        "allLecturesJson": {
          "edges": [
            {
              "node": {
                "index": 1,
                "date": "01/02/2018",
                "presenter": "Mary",
              }
            },
            {
              "node": {
                "index": 2,
                "date": "01/03/2018",
                "presenter": "Jack",
              }
            }]
      }
    }};
    
    const output = input.data.allLecturesJson.edges.reduce((accumulator, currVal) => {
      return [...accumulator, currVal.node];
    }, []);
    
        4
  •  0
  •   Rohìt Jíndal    8 年前

    Array.map() Arrow

    var jsonObj = {
      "data": {
        "allLecturesJson": {
          "edges": [
            {
              "node": {
                "index": 1,
                "date": "01/02/2018",
                "presenter": "Mary",
              }
            },
            {
              "node": {
                "index": 2,
                "date": "01/03/2018",
                "presenter": "Jack",
              }
            }
          ]
        }
      }
    };
    
    var res = jsonObj.data.allLecturesJson.edges.map(obj => obj.node);
    
    console.log(res);