Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, we will learn to add an array in an object in javascript, here we will use some common syntax of an object to store an array to an object.

To add an array in the object, we will use object add elements syntax, where we have to just assign an array to an object like assign to any variable.

Well, let’s start the today’s tutorial How to append an array to object in javascript?

Here, we will create the first two variables with sample data of an object and array.

// your sample array
const arrList = ['A', 'B', 'C'];

// your sample object
const objList = {
  number: [1, 2, 3]
}

Now, we will assign array data in the object, and as we know we need to define some key-like variable to store an array in an object.

Okay, then we will add an array as a alphabets key.

Append array at the creation of an object

Below example based on the initial time of the object like when we create an object, then how we can add an array to the object.

// your sample array
const arrList = ['A', 'B', 'C'];

// your sample object
const objList = {
  numbers: [1, 2, 3],
  alphabets: arrList,
}

console.log(objList)
javascript, append array to object at intial time example
javascript, append array to object at intial time example

Append array after the creation of an object

Below example based on how can we add an array after an object is declared and used.

Let’s see, getting more interesting.

// your sample array
const arrList = ['A', 'B', 'C'];

// your sample object
const objList = {
  numbers: [1, 2, 3],
  alphabets: arrList,
}

console.log(objList)
javascript, append array to object after creation example
javascript, append array to object after creation example

I hope it’s help you, All the best 👍.