解释起来相当复杂,所以我会尽量说得清楚。
我有一个对象 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/