SkyWalker
SkyWalker

Reputation: 14317

What's the commended way/library to transform a Json?

I have a Web Service that returns the following Json:

[{"DailyHedge": "1.3414894654050926"}, 
 {"OptimalHedge": "1.6788094119827568"}]

and for the purpose of plotting it using d3js I need to transform it to:

[{"category": "DailyHedge", "measure": 1.3414894654050926}, 
 {"category": "OptimalHedge", "measure": 1.6788094119827568}]

I have been skimming over underscore.js but in general I am not sure about what to use for this ..

Upvotes: 1

Views: 59

Answers (2)

Adam Copley
Adam Copley

Reputation: 1495

Heres an implementation with plain javascript:

var data = [{"DailyHedge": "1.3414894654050926"},
 {"OptimalHedge": "1.6788094119827568"}];

var newdata = [];

for(let key in data)
{
    let obj = data[key];

    Object.keys(obj).forEach(key => {

        var row = {"category": key, "measure": obj[key]};

        newdata.push(row);

    });
}

console.log(newdata);

Upvotes: 1

Gerardo Furtado
Gerardo Furtado

Reputation: 102208

You can do it with plain, vanilla JavaScript, but since you're using D3, this can be done with d3.keys and d3.values.

According to the API, 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 d3.values:

Returns an array containing the property values of the specified object (an associative array). The order of the returned array is undefined.

Here is a demo:

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>

In vanilla JavaScript, just use Object.keys and Object.values. However, Object.values doesn't work on IE, Opera or Safari. An alternative is using a for...in loop.

Upvotes: 3

Related Questions