Reputation: 137
I have an array of objects which looks like this
[{center_name:"AXCG", 1_to_2years:34, 3_to_4years:12, 5_to_6years:45},
{center_name:"BDGT", 1_to_2years:67, 3_to_4years:23, 5_to_6years:45}]
Expected Result:
[
{"key":"AXCG","values":[
{"interval":'1_to_2years',"value":34},
{"interval":'3_to_4years',"value":12},
{"interval":'5_to_6years',"value":45},
]},
{"key":"BDGT","values":[
{"interval":'1_to_2years',"value":34},
{"interval":'3_to_4years',"value":12},
{"interval":'5_to_6years',"value":45},
]}]
After using d3.nest, I could get center_names as keys how do I transpose the values
var nested_data = d3.nest()
.key(function(d) { return d.center_name; })
.entries(output_array);
Upvotes: 0
Views: 115
Reputation: 12707
You can transform your old array into the new structure in various ways. Here is one of them:
var data = [
{center_name:"AXCG",
"1_to_2years":34,
"3_to_4years":12,
"5_to_6years":45},
{center_name:"BDGT",
"1_to_2years":67,
"3_to_4years":23,
"5_to_6years":45}
];
var new_data = []; //start with an empty array
//loop through original data item-by-item
data.forEach(function(d){
var obj = {}; //prepare an empty object
obj.key = d.center_name;
obj.values = []; // prepare internal empty array
//we need the key values from the object
Object.keys(d).forEach(function(key){
// but only keys that contain the word (year)...
if(key.indexOf("years")>-1){
//setting up the new data structure
obj.values.push({interval:key,value:d[key]});
}
});
// finally, pushing the object to the new array
new_data.push(obj);
});
console.log(new_data);
Upvotes: 1