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
user818700
4 Answers 4
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
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
gurvinder372
68.6k11 gold badges78 silver badges98 bronze badges
Comments
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
johni
5,5886 gold badges47 silver badges73 bronze badges
Comments
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
Harpreet Singh
2,67123 silver badges31 bronze badges
1 Comment
Harpreet Singh
@TaoP.R.O.P asked for it
lang-js