Javascript:向不同大小的数组添加 0 值

标签 javascript arrays object highcharts underscore.js

解释起来相当复杂,所以我会尽量说得清楚。

我有一个对象 data,它是一个对象数组,其中包含一个对象数组和一个字符串:

var groups = [
    { 
        bars: [
            {label: 'a', value: 28},
            {label: 'c', value: 16}
        ],
        string: 'one'
    },
    {
        bars: [
            {label: 'a', value: 3},
            {label: 'b', value: 17},
            {label: 'c', value: 24}
        ],
        string: 'two'
    },
    {
        bars: [
            {label: 'a', value: 12},
            {label: 'd', value: 7},
            {label: 'e', value: 36}
        ],
        string: 'three'
    },
    {
        bars: [
            {label: 'c', value: 32},
            {label: 'e', value: 2}
        ],
        string: 'four'
    }
] 

我需要所有“条”对象具有相同的大小,并且如果所述标签的对象不存在,则具有 0 值。正如您所看到的,与“bars”关联的标签键是一个有限列表。我的主要问题是“groups”对象的大小以及“bars”对象的大小是动态的。带下划线,我使用过:

var labelNames = _.uniq(_.flatten
    (_.map(data.groups,function(groups) {
    return _.pluck(groups.bars, 'label');
})));

提取给我的已知标签列表

['a', 'b', 'c', 'd', 'e']

我现在想将此数组映射到 bar 对象,给出以下输出:

var groups = [
    { 
        bars: [
            {label: 'a', value: 28},
            {label: 'b', value: 0},
            {label: 'c', value: 16},
            {label: 'd', value: 0},
            {label: 'e', value: 0}
        ],
        string: 'one'
    },
    {
        bars: [
            {label: 'a', value: 3},
            {label: 'b', value: 17},
            {label: 'c', value: 24},
            {label: 'd', value: 0},
            {label: 'e', value: 0}
        ],
        string: 'two'
    },
    {
        bars: [
            {label: 'a', value: 12},
            {label: 'b', value: 0},
            {label: 'c', value: 0},
            {label: 'd', value: 7},
            {label: 'e', value: 36}
        ],
        string: 'three'
    },
    {
        bars: [
            {label: 'a', value: 0},
            {label: 'b', value: 0},
            {label: 'c', value: 32},
            {label: 'd', value: 0},
            {label: 'e', value: 2}
        ],
        string: 'four'
    }
]

如果有帮助,我必须有偶数条,因为我已经使用这些对象创建了一个 highcharts 系列 like this example 。 我希望这是有道理的。任何帮助,将不胜感激。我一直在疯狂地试图解决这个问题。

最佳答案

这就是我为那些偶然发现这一点的人所做的。

_.each(data.groups, function(group) {
    var currentValues = _.pluck(group.bars, 'label');
    var zeroValues = _.difference(labelNames, currentValues);
    _.each(zeroValues, function(newLabel) {
        group.bars.push({label: newLabel, value: 0});
    });
}); 

关于Javascript:向不同大小的数组添加 0 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40516763/

相关文章:

java - 在java中一行声明多个对象

java - 在 ArrayList 中找不到对象

javascript - Javascript/jQuery 中的 Python 部分等价物

javascript - 使用 Material UI 和 ReactJS 提交和验证表单

javascript - 如何将名称中带有数组索引的对象属性合并到一个数组中?

javascript - 将查询结果传递到另一个页面的最佳方式

javascript - 循环遍历对象数组并返回这些对象的累积数据

javascript - 普通 javascript - 获取选中复选框的值

javascript - 尝试使用 'for' 循环构建数组

javascript - 解析 JSON - 数组的 json 数组