简体   繁体   English

Underscore.js将对象转换为数组

[英]Underscore.js convert object to array

I'm relatively new to underscore.js and I have an object coming in from a REST service which looks like this (I have typed it out by hand and assigned it to a var here): 我对underscore.js相对较新,我有一个来自REST服务的对象,看起来像这样(我手动输入并将其分配给var):

var production = [
    {key: ["wind", "1"], value: 5},
    {key: ["wind", "2"], value: 9},
    {key: ["wind", "3"], value: 11},
    {key: ["wind", "4"], value: 7},
    {key: ["solar", "1"], value: 1},
    {key: ["solar", "2"], value: 1},
    {key: ["solar", "3"], value: 2},
    {key: ["solar", "4"], value: 3},
    {key: ["oil", "1"], value: 15},
    {key: ["oil", "2"], value: 16},
    {key: ["oil", "3"], value: 22},
    {key: ["oil", "4"], value: 23},
];

Then further down, I have some code that parses this object and creates arrays for the items like so: 然后再往下,我有一些代码解析这个对象并为这些项创建数组,如下所示:

var orderedProduction = _.chain(production)
      .groupBy(function (entity) {
            return entity.key[0];
      })
      .map(function (values) { 
            return _.map(values, function (entity2) {
                  return entity2.value;
            });
      })
      .value();

This gives the following results: 这给出了以下结果:

orderedProduction  = [
  [5, 9, 11, 7],
  [1, 1, 2, 3],
  [15, 16, 22, 23]
]

Which loses the keys (wind/solar/oil). 哪个丢失了钥匙(风/太阳能/油)。 And is used to draw a graph. 并用于绘制图形。 I'm further able to check if some of these arrays meet a certain threshold like so: 我还能够检查其中一些阵列是否达到某个阈值,如下所示:

var threshold = _.map(orderedProduction  , function(arr) {
    return _.max(arr) > 10;
});

My requirements have now changed and I now need to filter out these arrays by its total sum, while retaining the key. 我的要求现在已经改变,我现在需要按总和来过滤掉这些数组,同时保留密钥。

What I would like to end up with an object like so: 我想最终得到一个像这样的对象:

orderedProduction  = {
      "wind": [5, 9, 11, 7],
      "solar": [1, 1, 2, 3],
      "oil": [15, 16, 22, 23]
    }

It would be great if the fix included a way to sum up the values of the array and remove those that do not total up to a certain amount. 如果修复程序包含一种总结数组值的方法并删除那些不总计达到一定数量的数组,那将会很棒。 (ie exclude solar, if it does not add up to 10). (即排除太阳能,如果不加10)。

Here is a jsfiddle I created to test this all out on: http://jsfiddle.net/2mfjw3jk/ 这是我创建的一个jsfiddle来测试这一切: http//jsfiddle.net/2mfjw3jk/


UPDATE: The solution I settled for was this: 更新:我解决的解决方案是:

var orderedProduction = _.chain(production)
    .groupBy(function (entity) {
        return entity.key[0];
    })
    .map(function (vals, key) {
        return [key, _.pluck(vals, 'value')]
    })
    .filter(function(arr) {
        var sum = 0;
        _.each(arr[1], function(num){
            sum += num;
        })
        return sum > 10;
    })
    .object()
    .value();

It also filters the values by a predetermined threshold (10 in this case). 它还将值过滤预定阈值(在这种情况下为10)。

You're almost there: 你快到了:

var orderedProduction = _.chain(production)
    .groupBy(function (entity) {
        return entity.key[0];
    })
    .map(function (vals, key) {
        return [key, _.pluck(vals, 'value')]
    })
    .object()
    .value();

returns 回报

{ wind: [ 5, 9, 11, 7 ],
  solar: [ 1, 1, 2, 3 ],
  oil: [ 15, 16, 22, 23 ] }

You can simply use the map() function provided in javascript. 您只需使用javascript中提供的map()函数即可。 The _.map() given is for backward compatibility. 给出的_.map()是为了向后兼容。 Anyways, here is the code : 无论如何,这里是代码:

var obj = {};
production.map(function(data) {
    if(data.key[0] in obj) {
        obj[data.key[0]] += data.value;
    } else {
        obj[data.key[0]] = 0;
        obj[data.key[0]] += data.value;
    }
});
console.log(obj);

So what is does is that it loops throught the production array. 那么它的作用就是循环生产数组。 There, it checks whether the key(for example, 'key' is the key) is in the obj object or not. 在那里,它检查密钥(例如,“密钥”是否是密钥)是否在obj对象中。 If it is there then it simply increments its value or else makes a new key and assigns it 0 and then increments it. 如果它在那里,那么它只是递增其值或者生成一个新密钥并将其赋值为0然后递增它。

Not the most optimized code but it works nicely. 不是最优化的代码,但它工作得很好。

This is probably not the best performing code, but it gets the job done using underscore. 这可能不是性能最佳的代码,但它使用下划线完成工作。

Live Demo 现场演示

var production = [
    {key: ["wind", "1"], value: 5},
    {key: ["wind", "2"], value: 9},
    {key: ["wind", "3"], value: 11},
    {key: ["wind", "4"], value: 7},
    {key: ["solar", "1"], value: 1},
    {key: ["solar", "2"], value: 1},
    {key: ["solar", "3"], value: 2},
    {key: ["solar", "4"], value: 3},
    {key: ["oil", "1"], value: 15},
    {key: ["oil", "2"], value: 16},
    {key: ["oil", "3"], value: 22},
    {key: ["oil", "4"], value: 23}
];

var orderedProduction =  _.chain(production)
    .groupBy(function (entity) {
        return entity.key[0];
    })
    .map(function(items, key){
        var returnVal = [key]; 
        var total = 0; 
        returnVal.push(_.map(items, function(obj){
            total += obj.value; 
            return obj.value; 
        })); 

        if(total > 10){
            return returnVal; 
        }

    })
    .filter(function(num) {
        return num !== undefined;
    })
    .object()
    .value();

console.log(production);
console.log(orderedProduction);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM