0

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!

1 Answer 1

1

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];
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

tymeJV, thank you for the tip. I'm not quite there yet...the data is not getting transformed. Here's what I changed my code to, on your suggestion: data.forEach( function(d) { if(!isNaN(d)) {d = +d} } );
Yes! Thank you so much! This is a great model from which I can finally understand the appropriate logic. Much appreciated.

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.