最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

Share Improve this question edited Jun 13, 2024 at 12:58 Oliver 9,5169 gold badges75 silver badges102 bronze badges asked Jul 27, 2016 at 8:55 Arjun AjithArjun Ajith 1,9206 gold badges25 silver badges47 bronze badges 5
  • 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 be array[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 be object.key, right? Then you already know how to access a field of the mth element of the nth element--just array[n][m].key, right? So what is your problem again? – user663031 Commented Jul 27, 2016 at 9:26
Add a ment  | 

3 Answers 3

Reset to default 6

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 (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);

发布评论

评论列表(0)

  1. 暂无评论