How Can I Convert a JavaScript Array to an Object?

Posted by

I’ll walk you through an example of converting an array in JavaScript to an object. You comprehend the idea of how to use JavaScript to transform an array to a JSON object. This post will provide you with a basic example of how to convert an array to an object in JavaScript. You can view the JavaScript convert array to object.

JavaScript will be used to turn the array into a JSON object using Object.assign(). To use Object.assign(), we simply need to supply the object as an argument. I’ll give you a very basic example of how to use jQuery to quickly turn an array into an object.

Let’s look at a quick example that should assist you:

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript Array to Object Convert</title>
</head>
<body>
  
<script>
      
    var myArray = [
        'one',
        'two',
        'three',
        'four',
        'five'
    ];
  
    var myObject = Object.assign({}, myArray);
  
    console.log(myObject);
  
</script>
  
</body>
</html>

Output:

{0: "one", 1: "two", 2: "three", 3: "four", 4: "five"}

 
0: "one"

1: "two"

2: "three"

3: "four"

4: "five"

__proto__: Object
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x