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?
This question is related to
javascript
You can use this function:
function createStringArray(arr, prop) {
var result = [];
for (var i = 0; i < arr.length; i += 1) {
result.push(arr[i][prop]);
}
return result;
}
Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.
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]);
}
}
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;
});
Source: Stackoverflow.com