JavaScript

Array Inside a JavaScript Object

The most popular data types in JavaScript are “objects” and “arrays”. You can combine both of them to form complex data structures that can handle and store a large amount of data in different formats. In JavaScript, an object may include arrays as properties that allow it to store and modify arrays within the context of the object.

This tutorial will demonstrate the procedure for using an array inside the Object.

How to Use Array Inside a JavaScript Object?

To use an array within a JavaScript object, simply declare an object with an array as one of its attributes. The object can then be utilized to access and manipulate the array. By making an array a property of an object, you can quickly add and remove elements from the array while keeping a reference to the object with which the array is connected.

Example

Create an object with five properties where two of them have arrays:

const obj = {
  id: 5,
  name: "Emily",
  designation: "Web Developer",
  skills: ["JavaScript", "Node", "Angular", "React"],
  team: []
};

Print the object on the console using the “console.log()” method:

console.log(obj);

The output shows all the properties including arrays and one of them is an empty array:

You can also access the array elements within the object using dot notation or bracket notation:

console.log(obj.skills);
console.log(obj["team"]);

Output

Here, we will access the first element of the “skills” array using “0” as array index:

console.log(obj.skills[0]);

As you can see, the output displays the “JavaScript” which is the first element of “skills” array:

You can also add or delete elements from an array in the object using the “push()” method. Here, we will add “Mili” in an empty array, and then print the array as an attribute of an object:

obj.team.push("Mili");
console.log(obj["team"]);

Output

We have gathered all the essential information related to the array inside a JavaScript object.

Conclusion

You can use an array in a JavaScript object, as one of its attributes. First, simply declare an object and add an array as a property of the object. The object can then be used for accessing and manipulating the array. This tutorial demonstrated the procedure for using an array inside the Object.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.