简体   繁体   中英

Extract array of key-values from JSON

How can I generate an array of a certain key-value pair from a nested JS object? Is there a lodash function to do this kind of thing?

Original data

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

Expected result

[
  {
    "index": 1,
    "date": "01/02/2018",
    "presenter": "Mary",
  },
  {
    "index": 2,
    "date": "01/03/2018",
    "presenter": "Jack"
  }
]
jsonData.data.allLecturesJson.edges.map(e => e.node)

这应该够了吧。

First of all your data is not well formatted. You have to format that to a valid object.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Try the following way with 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); 

We can use Array.prototype.reduce() to achieve the required data structure. No need to use lodash :)

Here is a function which transforms the structure:

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];
}, []);

You can achieve this with single line of code using Array.map() method with Arrow function expression.

Demo

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM