简体   繁体   中英

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":"markus.maier@mail.de",
    "externalId":"mmaie",
    "company":"Intel"
    },
    {
    "id":2,
    "firstName":"Birgit",
    "lastName":"Bauer",
    "email":"birgit.bauer@mail.de",
    "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!

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": "markus.maier@mail.de", "externalId": "mmaie", "company": "Intel" }, { "id": 2, "firstName": "Birgit", "lastName": "Bauer", "email": "birgit.bauer@mail.de", "externalId": "bbaue" }]; var emails = data.map(d => d.email); console.log(emails); 

Follow the code.loop through the data each object and for each object get the desired value by key.

 var data = [ { "id":1, "firstName":"Markus", "lastName":"Maier", "email":"markus.maier@mail.de", "externalId":"mmaie", "company":"Intel" }, { "id":2, "firstName":"Birgit", "lastName":"Bauer", "email":"birgit.bauer@mail.de", "externalId":"bbaue" } ]; for(var i=0; i< data.length;i++){ console.log(data[i]['email']); } 

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