Skip to content

Instantly share code, notes, and snippets.

@skl
Created January 29, 2024 16:51
Show Gist options
  • Save skl/b382e48f767abf5e1aa7d74bd7dc7e13 to your computer and use it in GitHub Desktop.
Save skl/b382e48f767abf5e1aa7d74bd7dc7e13 to your computer and use it in GitHub Desktop.
/**
* Takes a property path array, p, and a value, v, and returns an object to that spec.
*
* Example:
* objectify( ['foo', 'bar', 'baz'], [1, "42", {answer: 42}] )
*
* Would return an object literal in the form:
* {
* foo: {
* bar: {
* baz: [1, "42", {"answer": 42}]
* }
* }
* }
*
* @param {array} p Deep property path, e.g. ['foo', 'bar', 'baz'] becomes foo.bar.baz
* @param {any} v Any JSON serialisable value to assign to the above property
*/
objectify(p, v) {
if (!p || !p.length) {
return false;
}
return JSON.parse(
'{"' + p.join('":{"') + '":' + JSON.stringify(v) + '}'.repeat(p.length)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment