52

Is there a simple way, using filter or parse or something else to convert an array like the following :

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]
Ellone
  • 3,644
  • 12
  • 40
  • 72

4 Answers4

98

Use .map() function:

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

Snippet

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 is changed to make it work.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
20

A more minimal example (ES6 onwards):

someJsonArray.map(({id}) => id)
coatesap
  • 10,707
  • 5
  • 25
  • 33
1

You could do something like this:

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

console.log(output);
Keyboard ninja
  • 725
  • 6
  • 13
1

You can do this way:

var arr = [];
for(var i=0; i<someJsonArray.length; i++) {
    arr.push(someJsonArray[i].id);
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
shresha
  • 147
  • 10