benbenben
benbenben

Reputation: 159

Loading json data to an array in d3

so I am trying to assign json data to an array variable in d3.

Here is my json:

[
{
    "Impressions": "273909",
    "Clicks": "648",
    "CPM": 4.6388278388278,
    "Cost": 1266.4,
    "CPC": 1.9543209876543,
    "Campaign": "Campaign 1"
},
{
    "Impressions": "974408",
    "Clicks": "14571",
    "CPM": 4.0175975359343,
    "Cost": 3913.14,
    "CPC": 0.26855672225654,
    "Campaign": "Campaign 2"
},
{
    "Impressions": "76751",
    "Clicks": "5022",
    "CPM": 8.4675,
    "Cost": 643.53,
    "CPC": 0.1281421744325,
    "Campaign": "Campaign 3"
},

and here is my code to load the json dataset:

d3.json("DS003a_Adwords_AdPerformance_modified.json", function(error, data) {



var topData = data.sort(function(a, b){
    return d3.descending(+a.cost, +b.cost);
}).slice(0,10);

topData.forEach(function (d) {
    d.CampaignName = d.Campaign;
    d.cost = d.Cost;
});

var cost = d3.nest()
            .key(function(d) {return d.Cost;})
            .entries(data);  //fail


var p = d3.select("body").selectAll("p")
  .data(topData)
  .enter()
  .append("p")
  .text(function(d,i){
    return (i+1) + ". " + d.CampaignName + " cost = " + cost[i];
  });

I basically want to save the value of "Cost" to an array variable var cost. But when I tried my code the result is as followed:

enter image description here

What should i do?

Thank you, your help is appreciated :)

Upvotes: 1

Views: 3525

Answers (1)

tarulen
tarulen

Reputation: 2100

You cannot use nest to directly have an array of values. The two possible output formats of nest are:

  • a large object

    { 
     key1: value1, 
     key2: value2,
     ...
    }
    
  • or an array of small objects

    [ 
     { key: key1, values: value1 },
     { key: key2, values: value2 }, 
     ...
    ]
    

Neither is the one you desire. (Remember the first goal of nest: identify a set of keys, and group all pieces of data with the same key in a single batch, possibly with some transformation).

If for some reason you don't want to use your original array as suggested in the comments, then d3.map is what you're needing:

var cost = d3.map(data, function(d) {
   return d.cost;
});

This is creating a copy of your cost data (if your data array changes, then you will need to run d3.map again to update your array). So you should use this array only locally if your data may not be constant. This is why in general one prefers using the original data directly, as it also saves this copy step and has less risks of tricky bugs later on.

Upvotes: 1

Related Questions