JSFiddle - React, Tailwind, and code Playground

by ramnathv

HTML

<script src="https://rawgit.com/dataarts/dat.gui/master/build/dat.gui.min.js"></script>

JavaScript

var obj = { x: "mpg", y: "wt", z: 1};
var obj2 = {x: "mpg", y: "wt", z: {"a": 1, "b": 2}}
var obj = flatten(obj2)
var gui = new dat.GUI(),
    controllers = {}
gui.add(obj, 'x', ["mpg", "wt"])
gui.add(obj, 'y', ["mpg", "wt"])
var h = gui.add(obj, 'z.a', -3, 5)
h.onFinishChange(function(v){
  obj['z.a'] = v
  var obj2 = unflatten(obj)
  console.log(obj2)  
})
/*
controllers['z'] = gui.add(obj, 'z', -5, 5)
controllers['z'].onFinishChange(function(v){
  obj['z'] = v
  console.log(obj)  
})
*/



function flatten(target, opts) {
  opts = opts || {}

  var delimiter = opts.delimiter || '.'
  var output = {}

  function step(object, prev) {
    Object.keys(object).forEach(function(key) {
      var value = object[key]
      var isarray = opts.safe && Array.isArray(value)
      var type = Object.prototype.toString.call(value)
      var isobject = (
        type === "[object Object]" ||
        type === "[object Array]"
      )

      var newKey = prev
        ? prev + delimiter + key
        : key

      if (!isarray && isobject) {
        return step(value, newKey)
      }

      output[newKey] = value
    })
  }

  step(target)

  return output
}

function unflatten(target, opts) {
  opts = opts || {}

  var delimiter = opts.delimiter || '.'
  var result = {}

  if (Object.prototype.toString.call(target) !== '[object Object]') {
    return target
  }

  // safely ensure that the key is
  // an integer.
  function getkey(key) {
    var parsedKey = Number(key)

    return (
      isNaN(parsedKey) ||
      key.indexOf('.') !== -1
    ) ? key
      : parsedKey
  }

  Object.keys(target).forEach(function(key) {
    var split = key.split(delimiter)
    var key1 = getkey(split.shift())
    var key2 = getkey(split[0])
    var recipient = result

    while (key2 !== undefined) {
      if (recipient[key1] === undefined) {
        recipient[key1] = (
          typeof key2 === 'number' &&
          !opts.object ? [] : {}
        )
      }

      recipient = recipient[key1]
     ...