JSFiddle - React, Tailwind, and code Playground

by Shobhit Sharma

JavaScript

// convert the object to a string 
function otos(obj){
  var rs = '';
  var not_first = false;
  
  for(var k in obj){
    if(not_first) rs += ',';
    if(typeof obj[k] === 'object'){
      rs +=  '"'+k+'": {'+otos(obj[k])+'}';
    }
    else if(typeof obj[k] === 'string' || typeof obj[k] === 'function'){
      rs += '"'+k+'":"'+obj[k]+'"';
    }
    else if(typeof obj[k] === 'number'){
      rs += '"'+k+'":'+obj[k]+'';
    }
    else {
      // if it gets here then we need to add another else if to handle it
      console.log(typeof obj[k]);
    }
    not_first = true;
  }
  return rs;
}
// convert a string to object
function stoo(str){
  // we doing this recursively so after the first one it will be an object
  try{
    var p_str = JSON.parse('{'+str+'}');
  }catch(e){ var p_str = str;}
  
  var obj = {};
  for(var i in p_str){
    if(typeof p_str[i] === 'string'){
      if(p_str[i].substring(0,8) === 'function'){
        eval('obj[i] = ' + p_str[i] );
      }
      else {
        obj[i] = p_str[i];
      }
    }
    else if(typeof p_str[i] === 'object'){
      obj[i] = stoo(p_str[i]);
    }
  }
  return obj;
}

var obj = {
  'x-keys': {
    'z': function(e){console.log(e);},
    'a': [function(e){console.log('array',e);},1,2]
  },
  's': 'hey there',
  'n': 100
};
console.log(obj);

var original_obj = stoo(otos(obj));
original_obj['x-keys'].z('hey');
original_obj['x-keys'].a[0]('hey');
console.log('>>>', original_obj)