How do I convert a javascript object array to a string array of the object attribute I want? [duplicate]
Possible Duplicate:
Accessing properties of an array of objects
Given:
[{
'id':1,
'name':'john'
},{
'id':2,
'name':'jane'
}........,{
'id':2000,
'name':'zack'
}]
What's the best way to get:
['john', 'jane', ...... 'zack']
Must I loop through and push item.name
to another array, or is there a simple function to do it?
Solution 1:
If your array of objects is items
, you can do:
var items = [{
id: 1,
name: 'john'
}, {
id: 2,
name: 'jane'
}, {
id: 2000,
name: 'zack'
}];
var names = items.map(function(item) {
return item['name'];
});
console.log(names);
console.log(items);
Documentation: map()
Solution 2:
Use the map()
function native on JavaScript arrays:
var yourArray = [ {
'id':1,
'name':'john'
},{
'id':2,
'name':'jane'
}........,{
'id':2000,
'name':'zack'
}];
var newArray = yourArray.map( function( el ){
return el.name;
});
Solution 3:
You can do this to only monitor own properties of the object:
var arr = [];
for (var key in p) {
if (p.hasOwnProperty(key)) {
arr.push(p[key]);
}
}