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.name
to another array, or is there a simple function to do it?
我必须循环并将item.name推送到另一个数组,还是有一个简单的函数来执行它?
4 个解决方案
#1
63
If your array of objects is items
, you can do:
如果您的对象数组是项目,您可以执行以下操作:
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()
#2
4
Use the map()
function native on JavaScript arrays:
在JavaScript数组上使用native()函数:
var yourArray = [ {
'id':1,
'name':'john'
},{
'id':2,
'name':'jane'
}........,{
'id':2000,
'name':'zack'
}];
var newArray = yourArray.map( function( el ){
return el.name;
});
#3
1
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]);
}
}
#4
0
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实现中使用。
#1
63
If your array of objects is items
, you can do:
如果您的对象数组是项目,您可以执行以下操作:
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()
#2
4
Use the map()
function native on JavaScript arrays:
在JavaScript数组上使用native()函数:
var yourArray = [ {
'id':1,
'name':'john'
},{
'id':2,
'name':'jane'
}........,{
'id':2000,
'name':'zack'
}];
var newArray = yourArray.map( function( el ){
return el.name;
});
#3
1
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]);
}
}
#4
0
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实现中使用。