如何将 javascript 对象数组转换为我想要的对象属性的字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13973158/
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-24 15:18:12  来源:igfitidea点击:

How do I convert a javascript object array to a string array of the object attribute I want?

javascript

提问by PK.

Possible Duplicate:
Accessing properties of an array of objects

可能的重复:
访问对象数组的属性

Given:

鉴于:

[{
    'id':1,
    'name':'john'
},{
    'id':2,
    'name':'jane'
}........,{
    'id':2000,
    'name':'zack'
}]

What's the best way to get:

什么是最好的获得方式:

['john', 'jane', ...... 'zack']

Must I loop through and push item.nameto another array, or is there a simple function to do it?

我必须循环并推item.name送到另一个数组,还是有一个简单的函数来做到这一点?

回答by techfoobar

If your array of objects is items, you can do:

如果您的对象数组是items,则可以执行以下操作:

var items = [{
  id: 1,
  name: 'john'
}, {
  id: 2,
  name: 'jane'
}, {
  id: 2000,
  name: 'zack'
}];

var names = items.map(function(item) {
  return item['name'];
});

console.log(names);
console.log(items);

Documentation: map()

文档: map()

回答by Sirko

Use the map()function native on JavaScript arrays:

map()在 JavaScript 数组上使用本机函数:

var yourArray = [ {
    'id':1,
    'name':'john'
},{
    'id':2,
    'name':'jane'
}........,{
    'id':2000,
    'name':'zack'
}];

var newArray = yourArray.map( function( el ){ 
                                return el.name; 
                               });

回答by looper

You can do this to only monitor own properties of the object:

您可以这样做以仅监视对象自己的属性:

var arr = [];

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        arr.push(p[key]);
    }
}

回答by Minko Gechev

You can use this function:

您可以使用此功能:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

只需传递对象数组和所需的属性即可。上面的脚本即使在旧的 EcmaScript 实现中也能工作。