最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create array of values from array of objects - Stack Overflow

programmeradmin4浏览0评论

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' } ]

?

Share Improve this question asked Feb 14, 2012 at 14:57 Sergey MetlovSergey Metlov 26.4k28 gold badges96 silver badges154 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 11

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

发布评论

评论列表(0)

  1. 暂无评论