Created
January 29, 2024 16:51
-
-
Save skl/b382e48f767abf5e1aa7d74bd7dc7e13 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 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