Skip to content
Advertisement

How do you add multiple objects to an array? (JavaScript)

I’m not sure if I phrased the question right. I’m fairly new to JavaScript, and I’d like to add multiple objects (?) to an array. If I have this array:

JavaScript

How would I add, say

JavaScript

as

JavaScript

to the same array?

Advertisement

Answer

Items can be added to an array with the push method. Every array has this method build it, together with many other methods, and can be used to push a new value to the end of the array.

JavaScript

In the push method create an object with the keys and the values that you want to add.

JavaScript

If the keys of the object are the same name as the variables then you can use the syntax below. This will give the object keys with the same name as the variable and set the value of the variable with it as the value of the key.

JavaScript

Alternatively if you want to add an object to the beginning of the array, use the unshift method of the array.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement