Converting an Array to JSON Object in JavaScript

JSON, or “JavaScript Object Notation”, is one of the most popular data exchange formats, particularly in web development. If you have an array of data but the program you’re communicating with requires an object, don’t fear, we’ll go over some easy conversion methods.

Quick Answer – JS Array to JSON

Arrays are actually valid JSON, so if you just need to prepare your array in order to make a fetch request with it, it’s as easy as using the JSON.stringify() method.

const resp = await fetch('', {
    method: 'POST',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json'
    body: JSON.stringify([1, 2, 3, 4, 5])

The JSON.stringify() method converts a JavaScript object, array or value to a JSON string that can be sent over the wire using the Fetch API (or another communication library).

Weird Answer – Array to JSON with indexes as keys

If you didn’t want the direct string representation of a JSON array, perhaps you want an object where the keys are the indexes of the array. For example:

["apple", "orange", "banana"]

// becomes

  "0": "apple",
  "1": "orange",
  "2": "banana"

Having trouble finding a coding job? Need collaborators for your next project? Want to try to convince us Python > Golang? Join us in our free community Discord server to hang out.

To get a JSON object from an array with index keys you can use the Object.assign method in conjunction with `JSON.stringify` following code:

const array = ["apple", "orange", "banana"]
const jsonString = JSON.stringify(Object.assign({}, array))
// jsonString becomes
// {"0":"apple","1":"orange","2":"banana"} 

Thanks For Reading!

If you’re interested in furthering your CS career, take our computer science courses

Follow and hit us up on Twitter @q_vault if you have any questions or comments, and if we’ve made a mistake be sure to let us know so we can get it corrected!

Subscribe to our newsletter for more programming articles

%d bloggers like this: