Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - 从对象数组中提取属性值作为数组(From an array of objects, extract value of a property as array)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a shorter way of achieving it:

(这是实现它的一种较短的方法:)

let result = objArray.map(a => a.foo);

or

(要么)

let result = objArray.map(({ foo }) => foo)

You can also check Array.prototype.map() .

(您还可以检查Array.prototype.map() 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...