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.

Revisions

  1. skl created this gist Jan 29, 2024.
    27 changes: 27 additions & 0 deletions objectify.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    /**
    * 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)
    );
    }