0

I have a simple object:

   let obj = {
      season: 'winter',
      data: {
          month: ['December', 'January', 'February']
         }
    };

I need to get a string like:

`season=winter&data[month][0]=December&data[month][1]=January&data[month][2]=February`

I tried but I didn't completely succeed

  function convertToText(obj) {
   let string = [];
   if (typeof(obj) == "object") {
        for (prop in obj) {
            if (obj.hasOwnProperty(prop))
            string.push(prop + "=" + convertToText(obj[prop]));
        };
    return string.join("&");
    } else {
        string.push(JSON.stringify(obj))
    }

    return string.join();
}

and gets this:

"season='winter'&data=month=0='December'&1='January'&2='February'"
  • 3
    Does [this](https://stackoverflow.com/q/19098797/1048572) help? If not, please show us your attempt, or explain where exactly you are stuck at writing this function. – Bergi Oct 02 '22 at 16:50
  • 3
    [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) could also be helpful – Adam Jenkins Oct 02 '22 at 16:51
  • Voted to reopen, as the edits make this a reasonable question, and there is clearly an honest attempt provided. – Scott Sauyet Oct 02 '22 at 20:33
  • Question seems good but how deep can the nesting be? – ggorlen Oct 03 '22 at 22:50

0 Answers0