I am trying to dynamically create this data array for ZingCharts and am stumped.
Basically, I need to make this structure:
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"
},
}]
}, ]
}]
};
I don't know what the correct way of doing this is. I am tempted to do something like this:
result.push("text: '" + data[0].party + "'")
I need to do this with all 50 states, and the data is coming in a structure like this:
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,
}];
Any tips on what I should be searching for would be greatly appreciated. Thanks!
Use reduce
function and a hash table
to create the data structure that you desire:
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;}
Let me know your thoughts on this, thanks!