简体   繁体   中英

Create array of values from array of objects

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(",") );

如果你不介意使用Underscore.js(它包含更多的实用程序函数),那么你需要的是pluck函数。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM