0

I have an Object array that looks like the following:

var array = [
  {'id':1,'description':test},
  {'id':2,'description':test},
  {'id':3,'description':test}
]

And I want to convert it to look like this:

var newArray = [
  1, 2, 3
]

So it's basically taking the object array, extracting the id's out of the objects, and creating a new array that contains the id's that were extracted. Is there a way to do this in one line? Even better if a new array doesn't have to get created and array is just updated.

4 Answers 4

3

var test ="sai";
var array = [
  {'id':1,'description':test},
  {'id':2,'description':test},
  {'id':3,'description':test}
]

console.log(array.map(function(obj){return obj.id}))

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

Comments

0

iterate the array using foreach and populate newArray

var newArray = [];
array.forEach(funtion(element){
   newArray.push(element.id);
});
console.log( newArray );

Comments

0
array.map(function (item) { 
    return item["id"];
}

If you'd like to have anew instance of the mapped array:

var newarray = [];
array.forEach(function (item) {
    newarray.push(item["id"]);
}

Comments

0
array.map(function(element) {return element.id})

OP Requirement: better if array is just updated

array = array.map(function(element) {return element.id})

1 Comment

@TaoP.R.O.P asked for it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.