Search code examples
javascriptobjectjavascript-objects

Can I turn a Object.property into a String like "Object.property"?


I want to create a function to turn the keys from an object that i am accessing to a string, something like:


const test = {
  propertyOne: {
   propertyTwo: 0
  },
  propertyThree: {
   propertyFour: 0
  }
}


function ObjectKeysToString(objectReceived) {
  ...
  return stringfiedObjectReceived
}


Input: 

test.propertyOne.propertyTwo
ObjectKeysToString(test.propertyOne.propertyTwo)



Output: "test.propertyOne.propertyTwo"

Is this possible?

I've searched for this and looked for every Object method but didnt succeeded on any of them


Solution

  • The best you can do is propertyOne.propertyTwo. Variable names can't be accessed in runtime

    const test = {
      propertyOne: {
        propertyTwo: 0
      }
    }
    
    
    function ObjectKeysToString(objectReceived) {
      const path = []
      let current = objectReceived
      do {
        const key = Object.keys(current)[0]
        path.push(key)
        current = current[key]
      } while (typeof current === 'object' && current !== null)
    
      return path.join('.')
    }
    
    console.log(ObjectKeysToString(test))