Skip to content
Onsite

Lodash set

MediumP3Coding

Implement set(object, path, value), in the spirit of Lodash's _.set: write a value at a nested path, creating the missing parts. It modifies object and returns it.

  • path is a string like "a.b.c", "a[0].b" or "a[0][1]", or an array of keys.
  • Missing intermediate containers are created: an array when the next key is a non-negative integer ("0", "12"), otherwise a plain object.
  • An existing intermediate value that is an object or array is kept. If an intermediate value exists but is not an object (a number, string, null...), replace it with a new container.
  • Setting an existing path overwrites the value.
  • If any key in the path is "__proto__", do nothing and return object unchanged, so the call cannot pollute Object.prototype.

The path is non-empty and keys do not contain dots or brackets.

Example 1

Input
set({}, 'a.b[1].c', 5)
Output
{ a: { b: [undefined, { c: 5 }] } }

Constraints

  • Path length <= 100 keys

Hints

Run checks the 3 visible tests, Submit all 10.