javascript-如何动态创建数组以更新ZingChart树图
作者:互联网
我正在尝试为ZingCharts动态创建此数据数组,并且陷入困境.
基本上,我需要建立以下结构:
var series = [{
text: "Democratic",
style: {
backgroundColor: "blue"
},
children: [{
text: "California",
value: 55,
style: {
backgroundColor: "blue"
},
}, {
text: "Oregon",
value: 7,
style: {
backgroundColor: "blue"
},
}]
},
{
text: "Republican",
style: {
backgroundColor: "red"
},
children: [{
text: "Texas",
value: 38,
style: {
backgroundColor: "red"
},
}, {
text: "Georgia",
value: 16,
style: {
backgroundColor: "red"
},
}]
}, {
text: "TossUp",
style: {
backgroundColor: "grey"
},
children: [{
text: "Arizona",
value: 22,
style: {
backgroundColor: "grey"
},
}]
}, ]
}]
};
我不知道这样做的正确方法是什么.我很想做这样的事情:
result.push("text: '" + data[0].party + "'")
我需要对所有50个状态执行此操作,并且数据以这样的结构传入:
var data = [{
"color": "blue",
"party": "Democratic",
"text": "California",
"value": 55,
}, {
"color": "blue",
"party": "Democratic",
"text": "Oregon",
"value": 7,
}, {
"color": "red",
"party": "Republican",
"text": "Texas",
"value": 38,
}, {
"color": "red",
"party": "Republican",
"text": "Georgia",
"value": 16,
}, {
"color": "grey",
"party": "Democratic",
"text": "Arizona",
"value": 11,
}];
我应该寻找的任何提示将不胜感激.谢谢!
解决方法:
使用reduce函数和哈希表来创建所需的数据结构:
var data=[{color:"blue",party:"Democratic",text:"California",value:55},{color:"blue",party:"Democratic",text:"Oregon",value:7},{color:"red",party:"Republican",text:"Texas",value:38},{color:"red",party:"Republican",text:"Georgia",value:16},{color:"grey",party:"Democratic",text:"Arizona",value:11}];
var result = data.reduce(function(hash) {
return function(prev, curr) {
if (hash[curr.color]) {
hash[curr.color].children.push({
text: curr.text,
value: curr.value,
style: {
backgroundColor: curr.color
}
});
} else {
hash[curr.color] = {};
hash[curr.color].children = hash[curr.color].children || [];
prev.push({
text: curr.party,
style: {
backgroundColor: curr.color
},
children: hash[curr.color].children
});
hash[curr.color].children.push({
text: curr.text,
value: curr.value,
style: {
backgroundColor: curr.color
}
});
}
return prev;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper{top: 0;max-height: 100%!important;}
让我知道您对此的想法,谢谢!
标签:zingchart,charts,arrays,javascript 来源: https://codeday.me/bug/20191118/2024948.html