如何按字段名称列出JavaScript对象的属性

时间:2015-01-20 09:51:09

标签: javascript javascript-objects

我创建了一个这样的对象:

[
  Object {
    Username = "James", Password = "12345", Email = "james@test.com"
  },
  Object {
    Username = "Auric", Password = "12345", Email = "auric@test.com"
  }
]

检索属性名称列表的最佳方法是什么?即我想最终得到一些变量'键',以便:

Object = ["james@test.com", "auric@test.com"]

感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用.map

var data = data.map(function (el) {
   return el.Email
})

答案 1 :(得分:1)

你有一个对象数组,所以你需要遍历它然后返回你需要的值。

    var myObjects = [
    {
    "Username" : "James", 
    "Password" : "12345", 
    "Email" : "james@test.com"
    },
  {
    "Username" : "Auric", 
    "Password" : "12345", 
    "Email" : "auric@test.com"
  }
];


function getProps (key) {
    var values = [];
    myObjects.forEach(function (obj){
      values.push(obj[key]);
    });
    return values;
}

console.log(getProps('Email'));