I have JavaScript object array with the following structure:
(我有以下结构的JavaScript对象数组:)
objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
I want to extract a field from each object, and get an array containing the values, for example field foo
would give array [ 1, 3, 5 ]
.
(我想从每个对象中提取一个字段,并获取一个包含值的数组,例如foo
字段将给出array [ 1, 3, 5 ]
。)
I can do this with this trivial approach:
(我可以用这种简单的方法做到这一点:)
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 ]
Is there a more elegant or idiomatic way to do this, so that a custom utility function would be unnecessary?
(是否有更优雅或惯用的方式来执行此操作,从而不需要自定义实用程序功能?)
Note about suggested duplicate , it covers how to convert a single object to an array.
(关于建议的重复项的注释,它涵盖了如何将单个对象转换为数组。)
ask by hyde translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…