DEV Community

Dominic Myers
Dominic Myers

Posted on • Originally published at drmsite.blogspot.com on

Create an Object from dot notation

By Oleksandr Klymovych via scopio
Image by Oleksandr Klymovych

I was puzzled about this all afternoon. I came up with a terrible workaround using eval. Tonight, I did some more research and found this answer on StackOverflow. I've adapted it, and it seems to work a treat:

(() => {

  const obj = {}

  const expand = (output, mystr, value) => {
    const items = mystr.split(".") // split on dot notation
    let ref = output // keep a reference of the new object
    // loop through all nodes, except the last one
    for (let i = 0; i < items.length - 1; i++) {
      if (!ref[items[i]]) {
        // create a new element inside the reference
        ref[items[i]] = {}
      }
      ref = ref[items[i]] // shift the reference to the newly created object 
    }
    ref[items[items.length - 1]] = value // apply the final value
    return output // return the full object
  }

  const arr = [
    "thingOne.thingTwo.thingThree",
    "thingOne.thingTwo.thingFour",
    "thingyOne.thingyTwo.thingyThree",
    "thingyOne.thingyTwo.thingyFour"
  ]

  arr.forEach(a => {
    expand(obj, a, true)
  })

  console.log(obj)

})()

Enter fullscreen mode Exit fullscreen mode

I was nearly there on my tod, TBH, but wussed out at the end; this is lovely! It produces this object:

{
  "thingOne": {
    "thingTwo": {
      "thingThree": true,
      "thingFour": true
    }
  },
  "thingyOne": {
    "thingyTwo": {
      "thingyThree": true,
      "thingyFour": true
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)