如何将 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
How do I convert a javascript object array to a string array of the object attribute I want?
提问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
回答by Sirko
回答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 实现中也能工作。

