FrontendPro

19Implement set(object, "a.b.c", value)

easyAbout 15 minutesCodingobjectssecuritylodash

Problem

Implement set(object, path, value), like Lodash's _.set. It writes value at a nested path, creating any missing objects or arrays on the way, and returns the same object.

const config = {};
set(config, "theme.colors.primary", "#0071e3");
// { theme: { colors: { primary: "#0071e3" } } }

set(config, "plugins[0].name", "analytics");
// config.plugins is an array: [{ name: "analytics" }]

Requirements

  • path is a dot string, may use [index], or is an array of keys.
  • Create a missing step as an array when the next key is a number, otherwise as an object.
  • Replace a primitive that is in the way with a new object or array.
  • Never write through __proto__, constructor or prototype, so the function cannot pollute Object.prototype.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

Use the same parsing as get: an array is used as is; a string has [0] rewritten to .0, then is split on . with empty parts removed.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever