Skip to content
Advertisement

Turn an object to a square bracket string (not using JSON.stringify)

I have this Javascript object (that is created on-the-fly by my plugin code):

JavaScript

I don’t want to turn this object to a JSON string, but I want to turn this object into another object, but with each field represented by a string, like this:

JavaScript

Scenario:

  • I dont know how the original object will look like (or how deep it’ll be), since it’s part of a plugin and I have no idea how people will build their forms
  • I’m going to put this new object inside a FormData object, if it would only accept objects, it would be easier, because JSON can’t upload files, but FormData object can

Advertisement

Answer

As I said in the comments, you need a for...in [MDN] loop to iterate over the properties of the object and can use recursion to subsequently convert nested objects:

JavaScript

DEMO

Still, I would recommend using JSON.

If you want to handle files as well, you might have to add an additional check for File objects. You’d want them raw in the result object:

JavaScript

It could be that the File (FileList) constructor is named differently in IE, but it should give you a start.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement