55

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]
6
  • 6
    What about someJsonArray.map(function(o) { return o.id; }) ? Doc about map Commented Dec 16, 2015 at 10:09
  • I dont think return in a callback will even work. Commented Dec 16, 2015 at 10:11
  • 1
    @E.K Well try it then... Commented Dec 16, 2015 at 10:16
  • 1
    I have edited the code in the above question to make it easy for developers! LoL. That's a sample code, which doesn't work. Commented Dec 16, 2015 at 10:19
  • Yea, my bad for the forgotten quotes since there is no accessible variable for the example. Thx Commented Dec 16, 2015 at 10:25

4 Answers 4

103

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.

Sign up to request clarification or add additional context in comments.

Comments

22

A more minimal example (ES6 onwards):

someJsonArray.map(({id}) => id)

3 Comments

this does not work as per the requirement in the question
@LGAP - could you explain - I've retested it against what was asked for, and it produces the exact result?
This works, but how? What is the significant of first & second id?
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);

Comments

1

You can do this way:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.