Execute JS command using string

Asked

Viewed 378 times

0

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

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

the mistake you give me is this:

Uncaught Syntaxerror: Unexpected string

  • 1

    Or tried to use without an apostrophe? data.result[0][0].pedidos.length ?

  • 2

    maybe you can access as a datatable in c#. data.result[0]["Orders"]. length;

  • 1

    You can give an example of this JSON?

  • Is this string fixed, or is it in a variable? If it is fixed, why not just do data.result[0][0].Pedidos.length?

2 answers

2


Assuming that 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"]

0

var comando = eval("data.result[0][0].Pedidos.length");

or however you prefer

var variavel = "pedidos";
var comando = eval("data.result[0][0]."+variavel+".length");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.