JavaScript |迭代JSON对象并获取特定键的所有值

时间:2017-01-23 12:56:56

标签: javascript json loops object key

我有以下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"
    } ]

我想迭代这两个对象并获得" email"的价值。关键..最简单的方法是什么?谢谢!

2 个答案:

答案 0 :(得分:4)

如果您想最终得到一组电子邮件,您可能需要查看.map()函数。



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




答案 1 :(得分:2)

按照code.loop通过数据,每个对象和每个对象按键获得所需的值。



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']);
    }
&#13;
&#13;
&#13;