Execute command in JS using string

0

I have a command to get the size of my json, but I need to use a string to indicate which object I want to get the size of:

var comando = data.result[0][0].'Pedidos'.length;

The error you give me is this:

Uncaught SyntaxError: Unexpected string

    
asked by anonymous 17.03.2015 / 17:57

2 answers

2

Assuming your data has a type structure:

{                                 // data
    "result":[                    // data.result
        [                         // data.result[0]
            {                     // data.result[0][0]
                "Pedidos":[...]   // data.result[0][0].Pedidos
            },
            ...
        ],
        ...
    ]
}

You can get the size of the "Orders" array as follows:

data.result[0][0]['Pedidos'].length;

Where 'Pedidos' could also be in a variable:

var x = 'Pedidos';
data.result[0][0][x].length;

Every JavaScript object can have its properties accessed as if it were an associative array:

objeto.campo == objeto["campo"]
    
17.03.2015 / 18:35
0
var comando = eval("data.result[0][0].Pedidos.length");

or as you like

var variavel = "pedidos";
var comando = eval("data.result[0][0]."+variavel+".length");
    
23.03.2015 / 14:02