To add an object to an array in JavaScript, you can follow these steps:

  1. Use the Array.push() method.
  2. Provide one or more objects as arguments.
  3. This method appends one or more elements at the end of the array and returns the new length.

Here's an example:

const users = []

const obj = {
  name: 'John Doe',
  age: 23
}

users.push(obj)

console.log(users)
// [ { name: 'John Doe', age: 23 } ]

You can also add multiple objects to an array by passing them as separate arguments to the Array.push() method, as demonstrated below:

const users = []

const obj1 = { name: 'John Doe', age: 23 }
const obj2 = { name: 'Jane Doe', age: 31 }
const obj3 = { name: 'Alex Lee', age: 18 }

users.push(obj1, obj2, obj3)

console.log(users)
// [
//   { name: 'John Doe', age: 23 },
//   { name: 'Jane Doe', age: 31 },
//   { name: 'Alex Lee', age: 18 }
// ]

For further information on JavaScript arrays and storing multiple pieces of information in a single variable, you can read this article.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.