systemajik
systemajik

Reputation: 47

Loop through nested json array to create new array

I am working on a lambda function that GETs data from one API and POSTs it to another. The data is a list of contacts with properties, e.g. first name, last name, email, etc.

The JSON output contains too many properties that I don't need. See below code example (actual code contains many more properties and nested arrays/objects).

{
  "contacts": [
      {
          "addedAt": 1532803458796,
          "vid": 101
      }
   ],
  "merge-audits": [],
  "properties": {
       "first-name": {
          "value":"hello"
        },
        "last-name": {
          "value":"there"
        },
        "email": {
          "value":"[email protected]"
        }
... 
...
}

How can I loop through each JSON object to create a new, simpler JSON array like the following:

[
  {
    "email": "[email protected]",
    "first_name": "",
    "last_name": "User"
  },
  {
    "email": "[email protected]",
    "first_name": "Example",
    "last_name": "User"
  }
]

Thanks in advance for your help.

Upvotes: 1

Views: 703

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92743

try

json.map( x => ({
  email:      x.properties.email.value,
  first_name: x.properties['first-name'].value,
  last_name:  x.properties['last-name'].value,
}));

let json = [
{
  "contacts": [{
    "addedAt": 1532803458796,
    "vid": 101
  }],
  "merge-audits": [],
  "properties": {
    "first-name": {
      "value": "hello"
    },
    "last-name": {
      "value": "there",
    },
    "email": {
      "value": "[email protected]"
    }
  }
},
{
  "contacts": [{
    "addedAt": 1532803458796,
    "vid": 101
  }],
  "merge-audits": [],
  "properties": {
    "first-name": {
      "value": "Tom"
    },
    "last-name": {
      "value": "Smith",
    },
    "email": {
      "value": "[email protected]"
    }
  }
}
]

let r = json.map(x => ({
  email:      x.properties.email.value,
  first_name: x.properties['first-name'].value,
  last_name:  x.properties['last-name'].value,
}));

console.log(r);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386883

You could use a destructuring assignment for the object and short hand properties for the mapping.

var data = [{ contacts: [{ addedAt: 1532803458796, vid: 101 }], "merge-audits": [], properties: { "first-name": { value: "hello" }, "last-name": { value: "there" }, email: { value: "[email protected]" } } }],
    result = data.map(({ properties: {
        'first-name': { value: first_name },
        'last-name': { value: last_name },
         email: { value: email }
    } }) => ({ first_name, last_name, email }));

console.log(result);

Upvotes: 1

Related Questions