Is there any tool to to create:
[ 'John', 'Sam', 'Marry' ]
from:
[ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ]
?
Is there any tool to to create:
[ 'John', 'Sam', 'Marry' ]
from:
[ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ]
?
Yeah, the map()
method:
var array = [{name: 'John'}, {name: 'Sam'}, {name: 'Mary'}].map(function (val) {
return val.name;
});
or jQuery's version:
var array = jQuery.map([{name: 'John'}, {name: 'Sam'}, {name: 'Mary'}], function (val) {
return val.name;
});
The tool is called a for loop. A non jQuery solution.
var myArray = [];
var myObj = [ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ];
for( var x in myObj ) {
myArray.push( myObj[x].name );
}
alert( myArray.join(",") );
If you don't mind using Underscore.js (which consists of more utility functions), the pluck
function is what you're looking for.
var names = _.pluck(array, "name");
var input=[ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ];
var output=[];
$.each(input, function (index, value){
output.push(value.name);
});
Using for(...) as shown in a couple of the above answers works fine, but you also run the risk of adding members you don't want this way, or running into some errors when trying to grab the name property from a member that doesn't have that property. See: Why is using "for...in" with array iteration a bad idea?
var input=[ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ];
var output=[];
for (var i in input) output[output.length]=i.name;
var newArr = [];
for (var i = 0, max = arr.length; i < max ; i++) {
newArr.push(arr[i].name);
}
The above works without needing any libraries, and still works properly even if someone mucked with object prototypes