Skip to content

Instantly share code, notes, and snippets.

@citrus
Created November 10, 2021 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save citrus/7d8bac333c2ef55b9b60085d66346d65 to your computer and use it in GitHub Desktop.
Save citrus/7d8bac333c2ef55b9b60085d66346d65 to your computer and use it in GitHub Desktop.
Transform an object into an object with its values as deeply nested keys to themselves
const isLiteralObject = (object => !!object && object.constructor === Object)
function populateWithDotSyntax (object, parent = null) {
return Object.entries(object).reduce((obj, [ key, value ]) => {
const string = parent !== null ? `${parent}.${ key }` : key
if (isLiteralObject(value)) {
obj[key] = populateWithDotSyntax(value, string)
} else if (Array.isArray(value)) {
obj[key] = value.map((i, index) => populateWithDotSyntax(i, `${key}.${index}`))
} else {
obj[key] = `{{ ${string} }}`
}
return obj
}, {})
}
const data = {
simple: "Simple",
nested: {
one: "Nested One",
two: {
three: "Triple Nested"
}
},
array: [
{
title: 'Array First',
date: new Date()
},
{
title: 'Array Second',
date: new Date()
}
]
}
console.log(populateWithDotSyntax(data))
// {
// simple: '{{ simple }}',
// nested: { one: '{{ nested.one }}', two: { three: '{{ nested.two.three }}' } },
// array: [
// { title: '{{ array.0.title }}', date: '{{ array.0.date }}' },
// { title: '{{ array.1.title }}', date: '{{ array.1.date }}' }
// ]
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment