3

I am creating a scatter chart using D3. The input JSON for the chart stores data within quotes, making them strings, while i need it in integer or numeric format.

This is what i am getting,

var data = [{"collision_with_injury": "2500", "dist_between_fail": "12000"}]

This is what i need,

var data = [{collision_with_injury: 2500, dist_between_fail: 12000}]

Is there a function in D3 or Jquery to convert the data object to one without quotes?

4
  • Adam's comment helped me indirectly. I was not able to add the function as described but prefixing '+' to collision_with_injury and dist_between_fail where i am calling them, resolve it. thanks! '+' converts a string to integer Commented Sep 5, 2013 at 3:31
  • Why were you not able to add the function as described in Adam's comment? Commented Sep 5, 2013 at 3:39
  • Great! My answer was missing a closing parentheses; I've just edited it in. Commented Sep 5, 2013 at 3:39
  • That was it, my bad...i use notepad++ it doesn't give me hints of missing parenthesis. Thanks Adam and Yogesh! Commented Sep 5, 2013 at 4:37

2 Answers 2

4
data.forEach(function(d){
  d.collision_with_injury = +d.collision_with_injury;
  d.dist_between_fail = +d.dist_between_fail;
});

If there are more properties in the object that need to be cast as a number, you can iterate over them w/ d3.keys().

Sign up to request clarification or add additional context in comments.

Comments

0

Look at this fiddle.

var data = [{"collision with injury": "2500", "dist_between_fail": "12AS00"}];
var dataLength = data.length;
if(dataLength>0)
{
    var keys = d3.keys(data[0]);
    var keyLength = keys.length;
    for(var i = 0; i < dataLength; i++)
    {
        var datum = data[i];
        for(var j = 0; j < keys.length; j++)
        {
            var key = keys[j];
            if(!isNaN(datum[key])) datum[key]=+datum[key];
        }
    }
}

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.