我有JavaScript对象数组,具有以下结构:
objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
Run Code Online (Sandbox Code Playgroud)
我想提取一个包含key值的数组foo,结果值为[ 1, 3, 5 ].
我用琐碎的方法完成了这个,如下:
function getFields(input, field) {
var output = [];
for (var i=0; i < input.length ; ++i)
output.push(input[i][field]);
return output;
}
var result = getFields(objArray, "foo"); // returns [ 1, 3, 5 ]
Run Code Online (Sandbox Code Playgroud)
有没有更优雅和高效的方法来实现?
关于建议重复的注意事项,该问题询问如何将对象转换为数组,这个问题询问如何从对象数组中提取单个属性.
是否有一种简单的方法,使用filter或者parse其他东西来转换数组,如下所示:
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"}
];
Run Code Online (Sandbox Code Playgroud)
进入一个简单的数组,填充前一个数组中包含的对象的一个属性,如下所示:
[0, 1, 2]
Run Code Online (Sandbox Code Playgroud)