how to add two attay into object in javascript

How to Add Two Arrays into an Object in JavaScript

As a web developer, I have come across situations where I needed to add two arrays into an object in JavaScript. It can be done in different ways, but here are two ways that I have used:

Method 1: Using Object.assign()

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. We can use this method to add two arrays into an object in JavaScript.


const arr1 = ['apple', 'banana', 'cherry'];
const arr2 = ['dragon fruit', 'grapefruit'];

const myObj = Object.assign({}, arr1, arr2);
console.log(myObj); 
// Output: {0: "apple", 1: "banana", 2: "cherry", 3: "dragon fruit", 4: "grapefruit"}

In the above code, we have created two arrays 'arr1' and 'arr2'. We have initialized an empty object '{}' and used Object.assign() to add both arrays into this object. The resulting object 'myObj' contains all the elements of both arrays.

Method 2: Using Spread Operator

The spread operator (...) can be used to spread the elements of an array into a new array or an object. We can use this operator to add two arrays into an object in JavaScript.


const arr1 = ['apple', 'banana', 'cherry'];
const arr2 = ['dragon fruit', 'grapefruit'];

const myObj = {...arr1, ...arr2};
console.log(myObj); 
// Output: {0: "apple", 1: "banana", 2: "cherry", 3: "dragon fruit", 4: "grapefruit"}

In the above code, we have created two arrays 'arr1' and 'arr2'. We have used the spread operator (...) to spread the elements of both arrays into a new object 'myObj'. The resulting object 'myObj' contains all the elements of both arrays.

Both methods achieve the same result, however, it's important to choose the one that best fits your project requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe