Sergey Metlov
Sergey Metlov

Reputation: 26291

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

?

Upvotes: 4

Views: 188

Answers (6)

Matt
Matt

Reputation: 75307

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;
});

Upvotes: 11

pimvdb
pimvdb

Reputation: 154818

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

Upvotes: 2

phatskat
phatskat

Reputation: 1815

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?

Upvotes: 1

goat
goat

Reputation: 31813

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

Upvotes: 0

Eugen Rieck
Eugen Rieck

Reputation: 65264

var input=[ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ];
var output=[];

for (var i in input) output[output.length]=i.name;

Upvotes: 0

epascarello
epascarello

Reputation: 207501

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

Upvotes: 4

Related Questions