Phoebe Phoebe - 25 days ago 6
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:

[{"file":"morning","row_total":"1095935","attr1":"79","attr2":""},
{"file":"noon","row_total":"221167","attr1":"174","attr2":"114"},
{"file":"night","row_total":"1317102","attr1":"253","attr2":"114"}]


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

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];
        }
    }
}