Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript | Iterate through JSON Object and get all the values for a specific key

I have following JSON:

  [ {
    "id":1,
    "firstName":"Markus",
    "lastName":"Maier",
    "email":"[email protected]",
    "externalId":"mmaie",
    "company":"Intel"
    },
    {
    "id":2,
    "firstName":"Birgit",
    "lastName":"Bauer",
    "email":"[email protected]",
    "externalId":"bbaue"
    } ]

I want to iterate through both objects and get the value of the "email" key.. what is the simplest way to do that? Thanks!

like image 790
MarkusFsx Avatar asked Dec 15 '22 01:12

MarkusFsx


1 Answers

If you want to end up with an array of just the emails, you may want to look into the .map() function.

var data = [{
  "id": 1,
  "firstName": "Markus",
  "lastName": "Maier",
  "email": "[email protected]",
  "externalId": "mmaie",
  "company": "Intel"
}, {
  "id": 2,
  "firstName": "Birgit",
  "lastName": "Bauer",
  "email": "[email protected]",
  "externalId": "bbaue"
}];

var emails = data.map(d => d.email);

console.log(emails);
like image 148
Sam Avatar answered Dec 17 '22 01:12

Sam