Javascript - A good way to create an array from an array of objects

I have an array of javascript objects:

array = [ {x:'x1', y:'y1'}, {x:'x2', y:'y2'}, ... {x:'xn', y:'yn'} ] 

I want to create a new array of only x values:

 [ 'x1', 'x2', ..., 'xn' ] 

I could do this easily in a for ... loop:

 var newarray = []; for (var i = 0; i < array.length; i++){ newarray.push(array[i].x); } 

... but I wonder if there is a way to make one liner for this using jquery or even plain javascript?

+4
source share
3 answers

You can do this with map :

 var newarray = jQuery.map(array, function (item) { return item.x; }); 
+10
source

ECMAScript 5 has its own map() method:

 var newArray = array.map(function(value) { return value.x; }); 

In FF, this should be even faster than a loop, but this is not the case for all browsers (Opera); others do not even support it (IE).

+3
source

Of course, to work with a lot of data, you can use jLinq (disclaimer: my project) to select and query your records and then return what you want.

Again, this is true when you work with many objects and make requests, but you can get some ideas by looking at the source code.

0
source

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


All Articles