Javascript Underscore.js 将对象转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25867016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:58:30  来源:igfitidea点击:

Underscore.js convert object to array

javascriptarraysobjectunderscore.js

提问by Husman

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. (i.e. 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)过滤值。

回答by georg

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 ] }

回答by shash7

You can simply use the map() function provided in javascript. The _.map() given is for backward compatibility. Anyways, here is the code :

您可以简单地使用 javascript 中提供的 map() 函数。给出的 _.map() 是为了向后兼容。无论如何,这是代码:

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. If it is there then it simply increments its value or else makes a new key and assigns it 0 and then increments it.

所以它的作用是循环遍历生产数组。在那里,它检查密钥(例如,'key' 是密钥)是否在 obj 对象中。如果它在那里,那么它只是增加它的值,或者创建一个新键并将其分配为 0,然后增加它。

Not the most optimized code but it works nicely.

不是最优化的代码,但效果很好。

回答by Brandon Boone

This is probably not the best performing code, but it gets the job done using underscore.

这可能不是性能最好的代码,但它使用下划线完成工作。

Live Demo

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);