Created
November 10, 2021 15:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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