Convert an array of objects to an array of properties

Is there an easy way using filter or parse or something else to convert the array as follows:

 var someJsonArray = [ {id: 0, name: "name", property: "value", otherproperties: "othervalues"}, {id: 1, name: "name1", property: "value1", otherproperties: "othervalues1"}, {id: 2, name: "name2", property: "value2", otherproperties: "othervalues2"} ]; 

into a simple array filled with one attribute of the objects contained in the previous array, like this:

 [0, 1, 2] 
+7
javascript arrays
source share
3 answers

Use .map() :

 finalArray = someJsonArray.map(function (obj) { return obj.id; }); 

Excerpt

 var someJsonArray = [ {id: 0, name: "name", property: "value", therproperties: "othervalues"}, {id: 1, name: "name1", property: "value1", otherproperties: "othervalues1"}, {id: 2, name: "name2", property: "value2", otherproperties: "othervalues2"} ]; var finalArray = someJsonArray.map(function (obj) { return obj.id; }); console.log(finalArray); 

The above snippet has been modified to make it work.

+15
source share

You can do something like this:

 var len = someJsonArray.length, output = []; for(var i = 0; i < len; i++){ output.push(someJsonArray[i].id) } console.log(output); 
0
source share

You can do this:

 var arr = []; for(var i=0; i<someJsonArray.length; i++) { arr.push(someJsonArray[i].id); } 
0
source share

All Articles