DEV Community

Dominic Myers
Dominic Myers

Posted on Originally published at drmsite.blogspot.com on

Create dot notation array of strings from an Object

By Maxim Polak via scopio
Image by Maxim Polak

I created an object from an array of strings using dot notation last night. I did this because I had previously flattened an object into those strings. I spent a lot of time and effort trying to solve this problem, but then I asked a colleague if they could solve it using recursion. He did, and I'd like to share it here.

If we have this object:

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

Enter fullscreen mode Exit fullscreen mode

Then this code:

(() => {

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

  const getObjStringsArr = (o = {}, arr = [], name = '') => {
    Object.keys(o).forEach(key => {
      if (o[key] === true) {
        arr.push(`${name}${key}`)
      } else {
        const nested = getObjStringsArr(o[key], arr, `${name}${key}.`)
        arr.concat(nested)
      }
    });
    return arr
  }

  console.log(getObjStringsArr(obj))

})()

Enter fullscreen mode Exit fullscreen mode

It's brilliant having colleagues; it's even better having colleagues with giant brains! Thanks, Hamish!

It's not necessarily faster than my cludge, but it is far more elegant!

Top comments (0)