Javascript 将对象数组转换为属性数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34309090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:08:19  来源:igfitidea点击:

Convert array of objects into array of properties

javascriptarrays

提问by Ellone

Is there a simple way, using filteror parseor something else to convert an array like the following :

有没有一种简单的方法,使用filterparse或其他方法来转换如下数组:

var someJsonArray = [
  {id: 0, name: "name", property: "value", otherproperties: "othervalues"},
  {id: 1, name: "name1", property: "value1", otherproperties: "othervalues1"},
  {id: 2, name: "name2", property: "value2", otherproperties: "othervalues2"}
];

into a simple array filled with one attribute of the objects contained in the previous array like this :

放入一个简单的数组,其中填充了前一个数组中包含的对象的一个​​属性,如下所示:

[0, 1, 2]

回答by Praveen Kumar Purushothaman

Use .map()function:

使用.map()功能:

finalArray = someJsonArray.map(function (obj) {
  return obj.id;
});

Snippet

片段

var someJsonArray = [
  {id: 0, name: "name", property: "value", therproperties: "othervalues"},
  {id: 1, name: "name1", property: "value1", otherproperties: "othervalues1"},
  {id: 2, name: "name2", property: "value2", otherproperties: "othervalues2"}
];
var finalArray = someJsonArray.map(function (obj) {
  return obj.id;
});
console.log(finalArray);

The above snippet is changed to make it work.

对上面的代码段进行了更改以使其工作。

回答by Keyboard ninja

You could do something like this:

你可以这样做:

var len = someJsonArray.length, output = [];
for(var i = 0; i < len; i++){
   output.push(someJsonArray[i].id)
}

console.log(output);

回答by shresha

You can do this way:

你可以这样做:

var arr = [];
for(var i=0; i<someJsonArray.length; i++) {
    arr.push(someJsonArray[i].id);
}