【发布时间】:2017-03-23 20:11:39
【问题描述】:
解释起来很复杂,所以我会尽量明确。
我有一个对象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”关联的标签键是一个有限列表。我的主要问题是“组”对象的大小以及“条”对象的大小是动态的。带下划线,我用过:
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'
}
]
如果有帮助,我必须有偶数条,因为我已经用这些对象 like this example 创建了一个 highcharts 系列。 我希望这是有道理的。任何帮助,将不胜感激。我一直在疯狂地试图弄清楚这一点。
【问题讨论】:
-
用
_.each循环遍历groups的每个元素。使用_.pluck获取bars的所有标签,使用_.difference与已知标签之间的标签获取缺失的标签。然后添加带有这些标签和value: 0的元素。 -
谢谢!这让我大部分时间都在那里,所以我将其发布为答案
标签: javascript arrays object highcharts underscore.js