Phoebe Phoebe - 1 year ago 62
Javascript Question

Convert JSON values to number when key/values are dynamic

I'm using d3.json to decode a dataset where the key/values are unknown. I need to convert the number values to numbers and leave the rest alone.

My JSON looks like this:


It's read in from a PHP file with d3.json. For each value that can (without throwing NaN), I need to convert to a number (d3 uses the + symbol for this):

d3.json("getData.php", function(error, data) {
if (error) throw error;

data.forEach(function(d) {
if(!isNaN(d.i = +d.i)
d.i = +d.i

Obviously there's an issue with my testing/looping logic. I would really appreciate some guidance here.

Thank you!

Answer Source

isNaN will work on number strings - the assignment operator is probably throwing your code off - you can just do:

if(!isNaN(d.i)) {

You're also missing a second ) on your if statement with the isNaN check.

isNaN("1") //false
isNaN("x") //true

Suppose I should've read more. You need 2 loops - one to loop your array, the other to test the each key/val of the object your looping:

for (var i = 0; i < data.length; i++) {
    for (var key in data[i]) {
        if (!isNaN(data[i][key])) {
            data[i][key] = +data[i][key];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download