从对象数组中提取属性值作为数组

本文翻译自: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. 关于建议的重复项的注释,它涵盖了如何将单个对象转换为数组。


#1楼

参考:https://stackoom.com/question/1KCTh/从对象数组中提取属性值作为数组


#2楼

Yes, but it relies on an ES5 feature of JavaScript. 是的,但是它依靠JavaScript的ES5功能。 This means it will not work in IE8 or older. 这意味着它将无法在IE8或更低版本中使用。

var result = objArray.map(function(a) {return a.foo;});

On ES6 compatible JS interpreters you can use an arrow function for brevity: 在与ES6兼容的JS解释器上,为了简洁起见,您可以使用箭头功能

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

Array.prototype.map documentation Array.prototype.map文档


#3楼

Using Array.prototype.map : 使用Array.prototype.map

function getFields(input, field) {
    return input.map(function(o) {
        return o[field];
    });
}

See the above link for a shim for pre-ES5 browsers. 有关ES5之前版本浏览器的填充程序,请参见上面的链接。


#4楼

It depends of your definition of "better". 这取决于您对“更好”的定义。

The other answers point out the use of map, which is natural (especially for guys used to functional style) and concise. 其他答案指出地图的使用是自然的(特别是对于习惯使用功能样式的人)并且简洁。 I strongly recommend using it (if you don't bother with the few IE8- IT guys). 我强烈建议使用它(如果您不打扰那些IE8-IT专家的话)。 So if "better" means "more concise", "maintainable", "understandable" then yes, it's way better. 因此,如果“更好”的意思是“更简洁”,“可维护”,“可理解”,那么它会更好。

In the other hand, this beauty don't come without additional costs. 另一方面,这种美丽并非没有额外费用。 I'm not a big fan of microbench, but I've put up a small test here . 我不是microbench的忠实拥护者,但是我在这里做了一个小测试 The result are predictable, the old ugly way seems to be faster than the map function. 结果是可以预测的,旧的丑陋方法似乎比map函数要快。 So if "better" means "faster", then no, stay with the old school fashion. 因此,如果“更好”的意思是“更快”,那么不,保留传统的流行。

Again this is just a microbench and in no way advocating against the use of map , it's just my two cents :). 同样,这只是一个微平台,绝不主张使用map ,这只是我的两分钱:)。


#5楼

Check out Lodash's _.pluck() function or Underscore's _.pluck() function. 查看Lodash的_.pluck()函数或_.pluck()_.pluck()函数。 Both do exactly what you want in a single function call! 两者都完全可以在单个函数调用中完成您想要的!

var result = _.pluck(objArray, 'foo');

Update: _.pluck() has been removed as of Lodash v4.0.0 , in favour of _.map() in combination with something similar to Niet's answer . 更新: _.pluck()从Lodash v4.0.0起已被删除 ,转而使用_.map()并结合了类似于Niet的答案 _.pluck() is still available in Underscore . _.pluck()_.pluck()中仍然可用

Update 2: As Mark points out in the comments , somewhere between Lodash v4 and 4.3, a new function has been added that provides this functionality again. 更新2:正如Mark 在注释中指出的那样,在Lodash v4和4.3之间的某个地方,添加了一个新功能,再次提供了此功能。 _.property() is a shorthand function that returns a function for getting the value of a property in an object. _.property()是一种简写函数,它返回用于获取对象中属性值的函数。

Additionally, _.map() now allows a string to be passed in as the second parameter, which is passed into _.property() . 此外, _.map()现在允许将字符串作为第二个参数传递进来,该字符串被传递到_.property() As a result, the following two lines are equivalent to the code sample above from pre-Lodash 4. 结果,以下两行等效于Lodash 4之前的上述代码示例。

var result = _.map(objArray, 'foo');
var result = _.map(objArray, _.property('foo'));

_.property() , and hence _.map() , also allow you to provide a dot-separated string or array in order to access sub-properties: _.property()以及_.map() ,还允许您提供一个以点分隔的字符串或数组,以便访问子属性:

var objArray = [
    {
        someProperty: { aNumber: 5 }
    },
    {
        someProperty: { aNumber: 2 }
    },
    {
        someProperty: { aNumber: 9 }
    }
];
var result = _.map(objArray, _.property('someProperty.aNumber'));
var result = _.map(objArray, _.property(['someProperty', 'aNumber']));

Both _.map() calls in the above example will return [5, 2, 9] . 上例中的两个_.map()调用都将返回[5, 2, 9] _.map() [5, 2, 9]

If you're a little more into functional programming, take a look at Ramda's R.pluck() function, which would look something like this: 如果您更喜欢函数式编程,请看一下R.pluck() R.pluck()函数,它看起来像这样:

var result = R.pluck('foo')(objArray);  // or just R.pluck('foo', objArray)

#6楼

Function map is a good choice when dealing with object arrays. 处理对象数组时,函数映射是一个不错的选择。 Although there have been a number of good answers posted already, the example of using map with combination with filter might be helpful. 尽管已经发布了许多好的答案,但结合使用带有过滤器的地图的示例可能会有所帮助。

In case you want to exclude the properties which values are undefined or exclude just a specific property, you could do the following: 如果要排除未定义值的属性或仅排除特定属性,可以执行以下操作:

    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/ https://jsfiddle.net/ohea7mgk/

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值