Skip to content
the poor coder

how to add two attay into object in javascript

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC