简体   繁体   中英

how to access object inside an object Array which is inside another array in javascript?

I have an array as follows

[
 [{"Id":"5","Color":"White"}],
 [{"Id":"57","Color":"Blue"}],
 [{"Id":"9","Color":"Brown"}]
]

each object is inside an array which is inside another array. I want to access an object item, let say 'Id' of first object ("Id":"5"). How can I do that?

If the array is assigned to a variable:

var a = [
 [{"Id":"5","Color":"White"}],
 [{"Id":"57","Color":"Blue"}],
 [{"Id":"9","Color":"Brown"}]
];

You can do it like this:

a[0][0].Id;

or

a[0][0]["Id"];

To get the second object you would do:

a[1][0].Id;

or

a[1][0].["Id"];

if it's javascript your object must be named (eg x)

Then select the index of the first array (here : 0, 1 or 2)

Then the "small" array content only one item, you have no choice, take 0.

For end, you can pick the property you need, Id or Color.

You have :

var myColor = x[1][0]["Color"];
console.log(myColor); //output : Blue

 var obj_c = [ [{"Id":"5","Color":"White"}], [{"Id":"57", "Color": "Blue"}], [{"Id":"9","Color":"Brown"}] ]; console.log(obj_c[0][0].Id); console.log(obj_c[0][0].Color); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM