How to push an array into the object in JavaScript ?


In JavaScript, we can push an array into an object using the following methods:

Method 1: Using dot notation We can use the dot notation to add a new property to the object and assign the array to it.

Example:

let obj = { name: "John", age: 30 };
obj.array = [1, 2, 3];
console.log(obj); // { name: "John", age: 30, array: [1, 2, 3] }

Method 2: Using square bracket notation We can also use the square bracket notation to add a new property to the object and assign the array to it.

Example:

let obj = { name: "John", age: 30 };
obj["array"] = [1, 2, 3];
console.log(obj); // { name: "John", age: 30, array: [1, 2, 3] }

Method 3: Using Object.assign() We can use the Object.assign() method to merge the object with a new object containing the array.

Example:

let obj = { name: "John", age: 30 };
let newObj = Object.assign({}, obj, { array: [1, 2, 3] });
console.log(newObj); // { name: "John", age: 30, array: [1, 2, 3] }

Method 4: Using spread operator We can use the spread operator to create a new object with the existing properties and add a new property with the array.

Example:

let obj = { name: "John", age: 30 };
let newObj = { ...obj, array: [1, 2, 3] };
console.log(newObj); // { name: "John", age: 30, array: [1, 2, 3] }


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.