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.

asked Jan 13, 2016 at 7:12

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}))

answered Jan 13, 2016 at 7:16
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 );
answered Jan 13, 2016 at 7:15

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"]);
}
answered Jan 13, 2016 at 7:15

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})
2pha
10.2k2 gold badges32 silver badges48 bronze badges
answered Jan 13, 2016 at 7:15

1 Comment

@TaoP.R.O.P asked for it

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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