JS Built-ins
← Array156 / 226
ArrayArray.prototype.reduceRightadvanced

Array.prototype.reduceRight() β€” build a nested object

πŸ“– Usage Example
const obj = {a: {b: {c: 42}}}
['a', 'b', 'c'].reduce((acc, key) => acc[key], obj)  // β†’ 42

Use reduce() (or reduceRight()) to safely drill into a nested object with a path array.

Building nested objects with reduceRight

Given keys ['a', 'b', 'c'] and a value, build a deeply nested object: { a: { b: { c: value } } }.

reduceRight() lets you wrap from the inside out.

buildNested(['a', 'b', 'c'], 42) // { a: { b: { c: 42 } } }
πŸ’‘ Hints (3)
  • β€’ Use `val` as the initial accumulator β€” it becomes the deepest value.
  • β€’ Wrap the accumulator with each key: `(acc, key) => ({ [key]: acc })`.
  • β€’ Computed property syntax `{ [key]: acc }` creates an object with a dynamic key.