1

I have a javascript code below:

function init() {
   var data_pie = [];
   var data_key = [];

   data_pie.push(10,12,30,40,80,25);        
   data_key.push("x1","x2","x3","x4","x5","x6");        
   g.update(data_pie, data_key);
}

update: function(data, key) {
   var i=-1;

   var streakerDataAdded = d3.range(data.length).map(function() {
     i++;
       return {
         name: key[i],
         totalPlayers: data[i]
       }
   });
}

How can I optimize my code to use this object:

var data='{"data":[{"x1":"10","x2":"12","x3":"30","x4":"40","x5":"80","x6":"25"}]}';

Instead data_pie and data_key arrays?

1
  • The variable you are trying to use is a JSON object. Have a look at this website and see what you can come up with: json.org/js.html Commented Jan 15, 2013 at 7:16

2 Answers 2

1

Without being able to test this (not having any access to the rest of your code), you might try something like:

function init() {
   var data='{"data":[{"x1":"10","x2":"12","x3":"30","x4":"40","x5":"80","x6":"25"}]}';

   for(key in data.data[0]){        
       g.update(data.data[0][key], key, data.data[0].length);
   }
}

update: function(data, key, length) {    
   var streakerDataAdded = d3.range(length).map(function() {
       return {
         name: key,
         totalPlayers: data
       }
   });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Update function should be called once.
0

It is very unclear as to why you would use such a data structure but anyway, here we go:

var jsonData = '{"data":[{"x1":"10","x2":"12","x3":"30","x4":"40","x5":"80","x6":"25"}]}';
// var cleanerJsonData = '{"x1":"10","x2":"12","x3":"30","x4":"40","x5":"80","x6":"25"}';

function update(json){
    var data = JSON.parse(json).data[0]; // why use an array here?
    // var data = JSON.parse(json) - using cleanerJsonData. 
    var streakerDataAdded = d3.map(data).entries().map(function(d){
        return {name: d.key, totalPlayers: d.value} })
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.