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 one of the object's properties, let say Id
of first object ("Id":"5"). How can I do that?
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 one of the object's properties, let say Id
of first object ("Id":"5"). How can I do that?
- What have you tried? – nicael Commented Jul 27, 2016 at 8:56
-
3
Suppose, If you hold the array in a variable called
x
, Then the required element can be fetched by,x[0][0]["Id"]
– Rajaprabhu Aravindasamy Commented Jul 27, 2016 at 8:56 - That's just a regular nested for / foreach. Did you try something first? jsfiddle/spev9pw6 – briosheje Commented Jul 27, 2016 at 8:56
-
1
outerArray[indexOfInnerArray][0].propertyName
– ysurilov Commented Jul 27, 2016 at 8:59 -
1
Very puzzled by where you are stuck. Do you know how to access the nth element of an array? If not, please study up on the basics of JavaScript arrays. You say
array[n]
, right? Then you already know how to access the mth element of the nth element; obviously that would bearray[n][m]
, right? Do you know how to access a field of an object? If not, then please study up on the basics of JavaScript objects. That would beobject.key
, right? Then you already know how to access a field of the mth element of the nth element--justarray[n][m].key
, right? So what is your problem again? – user663031 Commented Jul 27, 2016 at 9:26
3 Answers
Reset to default 6If 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 (e.g. 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);