Information



Tags



Share

How to use Multidimensional Arrays and Objects in JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement



While coding a function in JavaScript, you may need to get data in an array method for processing them in your function. But, especially for user information, it turns out a complicated job for you due to older entries tentatively named. To solve this problem, you can use javascript multidimensional arrays and objects; in this tutorial, I will show you how to use them to create a user database for one user also, if you want, you can use this method for server-side programming by extending it with PHP or Python.

How to use an array in JavaScript

There is more than one method for creating an array in JavaScript although you should use “[ ]” instead of other methods so I merely show “[ ]” in this tutorial.

You have to use index numbers to return variables held by arrays, starting 0.

// Define a new array for a new user.

var userInformation = ["John", "Doe", 35, "JohnDoe@email.com"];

document.getElementById("Output").innerHTML = userInformation[0];

Output: John

Multidimensional Arrays

To arrange subsidiary entries belonged to a specific user in the database and furthermore, to elicit this user information without searching for anything, you can use multidimensional arrays.

// Enter subsidiary entries - hobbies, skills, etc. - for this user who defined earlier.

var userInformation = [
["John", "Doe", 35, "JohnDoe@email.com"],
["Writing", "Baking", "Music", "Beekeeping"],
["Clerical", "Administrative", "Logical Thinking", "Problem Solving"]
];

document.getElementById("Output").innerHTML = userInformation[1][3];

Output: Beekeeping

Objects

Unlike arrays, objects use names to access its variables. In other words, you can define each variable by a specific name while entering them to an object.

Most importantly, you can implement multidimensional arrays into objects by giving them names - Hobbies, Skills, etc.

You should use objects when you want the element names to be strings (text).

You should use arrays when you want the element names to be numbers.(1)

Do not forget to write ":" after the defined name to register variables.

// Create an object to save all user information.

var userInformation = {
firstName: "John",
lastName: "Doe",
Age: 35,
Email: "JohnDoe@email.com",
Hobbies: ["Writing", "Baking", "Music", "Beekeeping"],
Skills: ["Clerical", ["new", "Administrative"], "Logical Thinking", "Problem Solving"]
};

document.getElementById("Output").innerHTML = userInformation.Skills[1][1];

// OR

document.getElementById("Output").innerHTML = userInformation["Skills"][1][1];

Output: Administrative

References

(1) https://www.w3schools.com/js/js_arrays.asp