Get Particular Object Property Within Javascript Array

I have some object within javascript array and I need to get all data only the name or whatever property inside the object. Usually I iterate entire array and append selected property into new empty array. Below is the code example.

var myList = [{name: 'foo', age: 21}, {name: 'bar', age: 15}, {name: 'john', age: 29}]
var listName = [];
for (var i = 0; i < myList.length; i++) {
    listName.push(myList[i].name);
}
console.log(listName); // [ 'foo', 'bar', 'john' ]

And code below is the alternative using map.

var myList = [{name: 'foo', age: 21}, {name: 'bar', age: 15}, {name: 'john', age: 29}];
var listName = myList.map(function(data){
    return data.name;
});
console.log(listName); // // [ 'foo', 'bar', 'john' ]

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s