从对象数组中,将属性的值提取为数组 [英] From an array of objects, extract value of a property as array

查看:165
本文介绍了从对象数组中,将属性的值提取为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript对象数组,结构如下:

I have JavaScript object array with the following structure:

objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];

我想提取一个包含key foo ,结果为 [1,3,5]

I want to extract an array containing the values of key foo, resulting in a value of [ 1, 3, 5 ].

我已经完成了这个用琐碎的方法,如下:

I have accomplished this with the trivial approach, as follows:

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 and performant method to accomplish?

关于建议重复的说明,该问题询问如何将对象转换为一个数组,这个问题询问如何从对象数组中提取单个属性

Note about suggested duplicate, that question asks how to convert an object to an array, this question asks how to extract single property from an array of objects.

推荐答案

这是实现它的一种较短方式:

Here is a shorter way of achieving it:

让结果= objArray.map(a => a.foo);

这篇关于从对象数组中,将属性的值提取为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆