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:

let arr = [{
  firstname: "John",
  lastname: "Smith"
}];

How would I add, say

var firstname = "John";
var lastname = "Doe";

as

{ firstname: "John",  lastname: "Doe" }

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.

var arr = [
  {
    firstname: "John",
    lastname: "Smith"
  }
];

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

var firstname = "John";
var lastname = "Doe";

arr.push({
  firsName: firstName,
  lastName: lastName
});

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.

arr.push({ firstName, lastName });

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

arr.unshift({ firstName, lastName });
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement