0

With Node JS, is it possible to set multi dimensional arrays separately, using key strings like in PHP ?

myArray[5]['age']      = 38;
myArray[5]['name']     = 'Jack';
myArray[5]['location'] = 'Australia';

I think this is confusing in Node JS:

var myArray = {};

myArray['usedId'] = new Array('Jack', 38, 'Australia');

because I had to do:

console.log (myArray[5]["0"]);

and I'd rather prefer to have a better control using:

console.log (myArray[5]['name']);

2 Answers 2

2

PHP arrays are weird and represent many data structures at once. An Array in JavaScript is closer to an traditional array although it is heterogeneous because of JavaScript's dynamic typing and probably other reasons.

Arrays in JavaScript use integer indices, but Objects in JavaScript represent key value pairs. These are what you want to use. You can have Arrays of Objects, and Object properties can contain arrays (and other objects).

myArray = [];
myArray[5] = {name: "Jack", age: "38", location: "Australia"};
console.log(myArray[5].name); // could also use ["name"]
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, and then, how do I append "Email" value ?
@JackM. the access notation is both readable and writable. You can include it in the myArray[5] = part, or you could do myArray[5].Email = "email"
Thanks again, just one more question: how would you get the myArray length ? In this case, would be 1 (key). The .length is giving me 0
@JackM. you shouldn't really do assignment like myArray[5] -- you should use .push or something to append to the array
@JackM. .push is just to add objects to myArray, not to add properties to the objects it contains.
|
2

Use an object, not an array:

myArray[5] = {
               name: 'Jack',
               age: 38,
               location: 'Australia'
             };

This will cause console.log (myArray[5]['name']); to work perfectly.

Also, your myArray is an object ({}), not an array ([]).

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.