HOW TO CONVERT ARRAY TO OBJECT IN JAVASCRIPT

Share the post

Hello All, In the last topic of the JAVASCRIPT tutorial, We had discussed reduce() & reduceRight() function in JavaScript. In this topic, We will discuss How to convert an array to an object in JAVASCRIPT. We will use spread operator (…) & Object.assign to convert array to object.

Spread Operator (…) Example

    let tempArr = [1, 5, 10, 40, 78];
    console.log(tempArr);

    //spread operator : now convert to object
    console.log({ ...tempArr });

Here, We are using the Spread operator before the array & It will give us an Object. Please see below the output

spread_operator_output
Output

Object.assign Example

    let tempArr = [1, 5, 10, 40, 78];
    console.log(tempArr);
    console.log(Object.assign({}, tempArr));

Here, We are using Object.assign & can able to convert given array into an object. please see below the output

object_assign_output
Output

By using the above two ways we can able to convert the array to object in JAVASCRIPT.

1 thought on “HOW TO CONVERT ARRAY TO OBJECT IN JAVASCRIPT”

Leave a Comment