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.
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}))
iterate the array
using foreach and populate newArray
var newArray = [];
array.forEach(funtion(element){
newArray.push(element.id);
});
console.log( newArray );
array.map(function(element) {return element.id})
OP要求:如果只是更新数组会更好
array = array.map(function(element) {return element.id})
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"]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.