Categories
JavaScript Answers

How to dynamically create nested objects using object names given by an array with JavaScript?

Spread the love

To dynamically create nested objects using object names given by an array with JavaScript, we use the reduce method.

For instance, we write

const set = (obj, path, val) => {
  const keys = path.split(".");
  const lastKey = keys.pop();
  const lastObj = keys.reduce((obj, key) => (obj[key] = obj[key] ?? {}), obj);
  lastObj[lastKey] = val;
};
const obj = { a: { prop: { that: "exists" } } };
set(obj, "a.very.deep.prop", "value");

to define the set function.

In it, we call split on the path to split the object path.

And then we get the last key with pop.

Then we call keys.reduce with a callback that returns sets the key property to an empty object if it doesn’t exist.

And then we set the lastKey of the nested property to val.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *