JSFiddle - React, Tailwind, and code Playground

by Evan Sharp

JavaScript

const flattenObject = ob => Object.keys(ob).reduce((toReturn, k) => {
  if (Object.prototype.toString.call(ob[k]) === '[object Date]') {
    toReturn[k] = ob[k].toJSON();
  }
  else if ((typeof ob[k]) === 'object' && ob[k]) {
    const flatObject = flattenObject(ob[k]);
    const isArray = Array.isArray(ob[k]);
    Object.keys(flatObject).forEach(k2 => {
      toReturn[`${k}.${isArray ? k2.replace(/^(\d+)(\..*)?/, '[$1]$2') : k2}`] = flatObject[k2];
    });
  }
  else {
    toReturn[k] = ob[k];
  }

  return toReturn;
}, {});

const obj = {spaceId: '13123', name: {first: 'something', last: 'anotherThing'}, more: { params: { dt: new Date(), other: ['a', 2, new Date(), {deep: 'ness', deeper: {than: 'ever', here: ['be', {dragons: '!!!'}]}}]}}};


const flat = flattenObject(obj);
  const fields = Object.keys(flat).map(key => {
    const name = key.replace(/\.\[\d+\]/g, '[]');
    const value = flat[key];
    return `<input type="hidden" name="${name}" value="${value}" />`;
  }).join('');
  
  console.log(fields);