Create an array of values ​​from an array of objects

Is there any tool to create:

[ 'John', 'Sam', 'Marry' ] 

from

 [ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ] 

?

+4
source share
6 answers

Yes, map() method :

 var array = [{name: 'John'}, {name: 'Sam'}, {name: 'Mary'}].map(function (val) { return val.name; }); 

or jQuery version :

 var array = jQuery.map([{name: 'John'}, {name: 'Sam'}, {name: 'Mary'}], function (val) { return val.name; }); 
+11
source

The tool is called a for loop. Solution without jQuery.

 var myArray = []; var myObj = [ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ]; for( var x in myObj ) { myArray.push( myObj[x].name ); } alert( myArray.join(",") ); 
+4
source

If you are not opposed to using Underscore.js (which consists of additional utility functions), the pluck function is what you are looking for.

 var names = _.pluck(array, "name"); 
+2
source
 var input=[ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ]; var output=[]; $.each(input, function (index, value){ output.push(value.name); }); 

Using for (...), as shown in several of the answers above, works fine, but you also run the risk of adding members you don't want, or getting confused by some errors when trying to grab a property name from a member that does not have this property. See: Why is using β€œfor ... in” with array iteration a bad idea?

+1
source
 var input=[ { name: 'John' }, { name: 'Sam' }, { name: 'Marry' } ]; var output=[]; for (var i in input) output[output.length]=i.name; 
0
source
 var newArr = []; for (var i = 0, max = arr.length; i < max ; i++) { newArr.push(arr[i].name); } 

The above works without any libraries and works correctly even if someone deleted prototypes of objects

0
source

Source: https://habr.com/ru/post/1396419/


All Articles