daniel__
daniel__

Reputation: 11845

loop with array data

i have this code to get three values.

 success: function(json){
                        $msg1 = parseFloat(json[0].valor1);
                        $msg2 = parseFloat(json[1].valor2);
                        $msg3 = parseFloat(json[2].valor3);
                    }

but now suppose that i need 200 values. I'm not doing 200 times ...

                        $msg1 = parseFloat(json[0].valor1);
                        $msg2 = parseFloat(json[1].valor2);
                        $msg3 = parseFloat(json[2].valor3);
                        //...
                        $msg200 = parseFloat(json[199].valor200);

so, i need a loop, correct?

i tried something like this

                        for (i=0; i<200; i++) {
                        $msg(i+1) = parseFloat(json[i].valor(i+1));
                        i++;
                        }   

but didn't work

thanks

Upvotes: 0

Views: 172

Answers (4)

Headshota
Headshota

Reputation: 21449

$msg = [];
for (var i=0; i<200; i++) {
    $msg.push(parseFloat(json[i]["valor"+i]));       
} 

Upvotes: 1

Pointy
Pointy

Reputation: 413712

This is why The Creator gave the world arrays.

var msgs = [];
for (var i = 0; i < 200; ++i)
  msgs.push(parseFloat(json[i]['valor' + i]));

Note that your JSON data should also keep those "valor" properties as arrays, though in JavaScript you can deal with a bizarre naming scheme like that as in the example above.

edit — oops, typos fixed :-)

Upvotes: 4

James Kyburz
James Kyburz

Reputation: 14453

var array = json.someid;// or json['someid'];
// json is returned not an array
var msgs = [];
$.each(array, function(index, e) {
    msgs.push(parseFloat[e['valor' + index], 10); 
});

when using parseFloat use the radix parameter unless you want bad things to happen;

javascript needs to be told for example not to parse octal;

Upvotes: 0

Marino Šimić
Marino Šimić

Reputation: 7342

As stated by Pointy or:

                var msgs = [];
                for (i=0; i<200; i++) {
                $msg[i] = parseFloat(eval('json[' + i + '].valor(' + i + '+1)'));
                i++;
                } 

However eval is slow, so Pointy's answer is better.

Upvotes: 0

Related Questions