0

Hey guys am new to javasript app development..I have learned about objects and arrays and i got that values in the arrays can be called by index but in objects it cant be possible.

So i have tried the code

name = ['dfsdf','sfdsf']
var b = [[name,'DFDSF']];
console.log(b[0].name);

It gives me undefined Instead of returning the array name.

I just want to know how can i access like b[index].nestedarrayname.

It would be really helpful if you provide some example codes ..Thanks

1
  • b will look like [[['dfsdf','sfdsf'], 'DFDSF']]. Values don't contain information about variable names. Commented Oct 21, 2014 at 17:43

3 Answers 3

1

If you want it to be an "associative" array, you would need to make the array element an object:

var b = [{name:'DFDSF'}];
console.log(b[0].name);
Sign up to request clarification or add additional context in comments.

1 Comment

that was helpful ..gonna accept this in minutes ..;)
0

as far as I undrestant , you want to cal name , which is an array itself , so :

 name = ['dfsdf','sfdsf']
 var b = [[name,'DFDSF']];

you can do :

 1 - console.log(b[0][0]); // this will output an array which contains ['dfsdf','sfdsf']

OR

you must change your structure to this :

 name = ['dfsdf','sfdsf']
 var b = [
           {"name": name} // the right one name, is your actual name array , so this is b[0]
           ,
          'DSDSF' // this is b[1]
         ];

now you can call:

   console.log(b[0].name);

NOTE :

in javascript , you can call an element iside an array by its index , and you can call a property inside an object in two ways :

1 - Using .(dot) like : object.property

2 - Using [''] like : object['property']

Comments

0

When you attempt to access a property via the . operator, JavaScript expects the object (an array in this case) to have an actual property with that name. Arrays have integer indexes in JavaScript, so to access it as-is you'll want:

console.log(b[0][0]);

However, if you do want an associative array, you can create the sub-indexes as objects instead (think JSON formatting):

var b = [{'name': name}, 'DFDSF'];
console.log(b[0].name); // b[0] is the object {'name': name}
                        // b[1] is the string 'DFDSF'

Comments

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.