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

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

我想从每个对象中提取一个字段,并获得一个包含值的数组,例如,字段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 ]

是否有更优雅或更惯用的方法来实现这一点,从而不需要自定义实用程序函数?


注意建议的重复,它介绍了如何将单个对象转换为数组。


当前回答

在ES6中,您可以执行以下操作:

const objArray = [{foo: 1, bar: 2}, {foo: 3, bar: 4}, {foo: 5, bar: 6}]
objArray.map(({ foo }) => foo)

其他回答

如果您希望ES6+中有多个值,以下操作将起作用

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

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

这是因为左边的{foo,baz}使用对象析构函数,而右边的箭头由于ES6的增强的对象文本而相当于{foo:foo,baz:baz}。

在处理对象数组时,函数映射是一个很好的选择。尽管已经发布了许多好的答案,但结合使用地图和过滤器的示例可能会有所帮助。

如果要排除值未定义的财产或只排除特定属性,可以执行以下操作:

    var obj = {value1: "val1", value2: "val2", Ndb_No: "testing", myVal: undefined};
    var keysFiltered = Object.keys(obj).filter(function(item){return !(item == "Ndb_No" || obj[item] == undefined)});
    var valuesFiltered = keysFiltered.map(function(item) {return obj[item]});

https://jsfiddle.net/ohea7mgk/

从对象数组中轻松提取多个财产:

let arrayOfObjects = [
  {id:1, name:'one', desc:'something'},
  {id:2, name:'two', desc:'something else'}
];

//below will extract just the id and name
let result = arrayOfObjects.map(({id, name}) => ({id, name}));

结果将是〔{id:1,名称:'one'},{id:2,名称:'two'}〕

根据需要在map函数中添加或删除财产

谈到纯JS的解决方案,我发现,尽管它可能很不优雅,但简单的索引for循环比它的替代方案更具性能。

从100000个元素数组中提取单个属性(通过jsPerf)

传统循环368操作/秒

var vals=[];
for(var i=0;i<testArray.length;i++){
   vals.push(testArray[i].val);
}

ES6用于。。循环303操作/秒

var vals=[];
for(var item of testArray){
   vals.push(item.val); 
}

Array.prototype.map 19操作/秒

var vals = testArray.map(function(a) {return a.val;});

TL;DR-.map()很慢,但如果您觉得可读性比性能更重要,可以使用它。

编辑#2:6/2019-jsPerf链接断开,已删除。

虽然map是从对象列表中选择“列”的适当解决方案,但它也有缺点。如果没有明确检查列是否存在,它将抛出一个错误,并(最多)为您提供undefined。我会选择reduce解决方案,它可以简单地忽略该属性,甚至为您设置默认值。

function getFields(list, field) {
    //  reduce the provided list to an array only containing the requested field
    return list.reduce(function(carry, item) {
        //  check if the item is actually an object and does contain the field
        if (typeof item === 'object' && field in item) {
            carry.push(item[field]);
        }

        //  return the 'carry' (which is the list of matched field values)
        return carry;
    }, []);
}

jsbin示例

即使提供的列表中的某个项不是对象或不包含该字段,这也会起作用。

如果项不是对象或不包含字段,甚至可以通过协商默认值来使其更加灵活。

function getFields(list, field, otherwise) {
    //  reduce the provided list to an array containing either the requested field or the alternative value
    return list.reduce(function(carry, item) {
        //  If item is an object and contains the field, add its value and the value of otherwise if not
        carry.push(typeof item === 'object' && field in item ? item[field] : otherwise);

        //  return the 'carry' (which is the list of matched field values)
        return carry;
    }, []);
}

jsbin示例

这与map相同,因为返回的数组的长度与提供的数组相同。(在这种情况下,地图比缩减略便宜):

function getFields(list, field, otherwise) {
    //  map the provided list to an array containing either the requested field or the alternative value
    return list.map(function(item) {
        //  If item is an object and contains the field, add its value and the value of otherwise if not
        return typeof item === 'object' && field in item ? item[field] : otherwise;
    }, []);
}

jsbin示例

还有一个最灵活的解决方案,它可以让你通过提供一个替代价值在两种行为之间切换。

function getFields(list, field, otherwise) {
    //  determine once whether or not to use the 'otherwise'
    var alt = typeof otherwise !== 'undefined';

    //  reduce the provided list to an array only containing the requested field
    return list.reduce(function(carry, item) {
        //  If item is an object and contains the field, add its value and the value of 'otherwise' if it was provided
        if (typeof item === 'object' && field in item) {
            carry.push(item[field]);
        }
        else if (alt) {
            carry.push(otherwise);
        }

        //  return the 'carry' (which is the list of matched field values)
        return carry;
    }, []);
}

jsbin示例

正如上面的示例(希望)揭示了这一工作方式,让我们通过使用Array.concat函数来稍微缩短该函数。

function getFields(list, field, otherwise) {
    var alt = typeof otherwise !== 'undefined';

    return list.reduce(function(carry, item) {
        return carry.concat(typeof item === 'object' && field in item ? item[field] : (alt ? otherwise : []));
    }, []);
}

jsbin示例