Reputation: 23
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
Upvotes: 1
Views: 49
Reputation: 24661
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))
Upvotes: 1