You have the option to accomplish this task using plain, vanilla JavaScript; however, given that you are utilizing D3, it can be achieved more efficiently with d3.keys
and d3.values
.
As specified in the API documentation, d3.keys:
Returns an array containing the property names of the specified object (an associative array). The order of the returned array is undefined.
And for d3.values:
Returns an array containing the property values of the specified object (an associative array). The order of the returned array is undefined.
Below is a demonstration:
var data = [{
"DailyHedge": "1.3414894654050926"
}, {
"OptimalHedge": "1.6788094119827568"
}];
var newData = [];
data.forEach(function(d) {
newData.push({
category: d3.keys(d)[0],
measure: +d3.values(d)[0]
});
});
console.log(newData)
<script src="https://d3js.org/d3.v4.min.js"></script>
If you opt for vanilla JavaScript, you can utilize Object.keys
and Object.values
. Nonetheless, please note that Object.values
is not compatible with IE, Opera, or Safari. An alternative approach would involve using a for...in
loop.