2

I am currently working on a website type project and I am new to JavaScript. So I have been having troubles with some parts of the syntax. Basically I am trying to print the 'id' and 'value' in the nested array arr.

var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})};
var obj = myArray[0];
document.write(obj.id);

this will print the id 1 but im not sure how to access id 10.

Also if there is an easier way to do this let me know please!

1
  • 1
    fyi, don't use new Array() but the [] array literal. Commented Mar 15, 2012 at 14:40

4 Answers 4

2

Firstly, don't use the new Array constructor. Just define an array literal [...]. So your myArray will look like:

var myArray = [{id:'1', value:'een', arr: [{id:'10', value:'een'}]}];

To get to the id of 10, you need to access myArray[0].arr[0].id;.

Sign up to request clarification or add additional context in comments.

2 Comments

[0], not [1] for the inner array
Don't ask why I wrote [1]. I have no idea XD
0

Proper reference would be:

obj.arr[0].id

PS: google chrome developer console is a goot playground for testing javascript object dereefrecing

2 Comments

If i wanted to initialize an array like this of size 10 by 10 how would i do so?
I would propose [] literals for this purpose, but it would be pretty werbose - but there is no way around. Usually such javascript arrays come from server from some kind of AJAX service ( JSON is syntactially valud javascipt literal and can be just evaluated), where they are converted automatically from some backend data model
0

You can't without iterating over the array.

If order does not matter, use an object instead:

var myObject = {
    1: {id:'1', value:'een'},
    10: {id:'10', value:'een'}
};
var obj = myArray[10];
document.write(obj.id);

In case the nesting in your array is intended, here's what you want:

var obj = myArray[0].arr[0];

Demo:

> var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})});
> myArray[0].arr[0]
{ id: '10', value: 'een' }

Comments

0

I would for get arrays why not create your own object ?

http://www.w3schools.com/js/js_objects.asp

1 Comment

I would like to create an array of objects but i wasn't sure how to do so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.