Sophea Phy
Sophea Phy

Reputation: 388

How to list the properties of a JavaScript object by field name

I create an object like this:

[
  Object {
    Username = "James", Password = "12345", Email = "[email protected]"
  },
  Object {
    Username = "Auric", Password = "12345", Email = "[email protected]"
  }
]

What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:

Object = ["[email protected]", "[email protected]"]

Thanks.

Upvotes: 0

Views: 127

Answers (2)

atmd
atmd

Reputation: 7490

You have an array of objects there, so you'll need to loop through that then return the values you need.

    var myObjects = [
    {
    "Username" : "James", 
    "Password" : "12345", 
    "Email" : "[email protected]"
    },
  {
    "Username" : "Auric", 
    "Password" : "12345", 
    "Email" : "[email protected]"
  }
];


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

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

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

You can use .map

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

Upvotes: 1

Related Questions