从Javascript中的对象列表中提取对象属性 [英] Extract object attribute from list of objects in Javascript

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

问题描述

我从API收到以下对象:

I have the following object that I'm receiving from an API:

{
   '2012-12-12': [
       { 'id': 1234,
         'type': 'A' },
       { 'id': 1235,
         'type': 'A' },
       { 'id': 1236,
         'type': 'B' },
    ],
   '2012-12-13': [
       { 'id': 1237,
         'type': 'A' },
       { 'id': 1238,
         'type': 'C' },
       { 'id': 1239,
         'type': 'B' },
    ]
}

然后我想要另一个名为类型 Array 的变量将保留所有可能的每个对象的类型属性的值。在这种情况下,它将是:

Then I want to have another variable named types of type Array that will hold every possible value of the type attribute of each one of the objects. In this case it would be:

types = ['A', 'B', 'C']

我正在尝试以功能方式完成它(我使用的是underscore.js)但我是无法找到一种方法。现在我正在使用

I'm trying to have it done in a functional way (I'm using underscore.js) but I'm unable to figure out a way of doing it. Right now I'm using

types = [];
_.each(response, function(arr1, key1) {
    _.each(arr1, function(arr2, key2) {
        types.push(arr2.type);
    });
});
types = _.uniq(types);

但这非常难看。你能帮我找出更好的编写代码的方法吗?

But that's very ugly. Can you help me in figuring out a better way of writing this code?

谢谢!

推荐答案

这应该有效:

types = _.chain(input) // enable chaining
  .values()            // object to array
  .flatten()           // 2D array to 1D array
  .pluck("type")       // pick one property from each element
  .uniq()              // only the unique values
  .value()             // get an unwrapped array

小提琴: http://jsfiddle.net/NFSfs/

当然,如果您愿意,可以删除所有空格:

Of course, you can remove all whitespace if you want to:

types = _.chain(input).values().flatten().pluck("type").uniq().value()

或不链接:

types = _.uniq(_.pluck(_.flatten(_.values(input)),"type"));






flatten似乎可以处理对象,即使文档明确指出它不应该。如果您希望针对实现进行编码,则可以省略对的调用,但我不建议这样做。实施可能会在一天内发生变化,导致您的代码被神秘地破坏。


flatten seems to work on objects, even though the documentation clearly states it shouldn't. If you wish to code against implementation, you can leave out the call to values, but I don't recommend that. The implementation could change one day, leaving your code mysteriously broken.

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

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