简体   繁体   English

将对象数组转换为字符串数组

[英]Convert Object array to String Array

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. 所以基本上走的是对象数组,提取id的出来的对象,并创建包含一个新的阵列id “中提取的秒。 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. 更妙的是,如果一个新的数组并没有得到建立和array是刚刚更新。

 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 使用foreach迭代array并填充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"]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM