ArticleZip > How To Create A Nested Object Given An Array Of Keys

How To Create A Nested Object Given An Array Of Keys

Creating a nested object from an array of keys is a handy trick that can help you structure your data in a more organized way. This technique comes in handy when you're working with complex data structures or need to represent hierarchical relationships in your code. In this article, I'll walk you through the steps to create a nested object from an array of keys in JavaScript.

Let's say you have an array of keys like this: `['key1', 'key2', 'key3']`, and you want to transform it into a nested object like this:

Javascript

{
  key1: {
    key2: {
      key3: {}
    }
  }
}

To achieve this, you can use a simple function that recursively builds the nested object. Here's how you can implement it:

Javascript

function createNestedObject(keys) {
  return keys.reduceRight((acc, key) => ({ [key]: acc }), {});
}

const keys = ['key1', 'key2', 'key3'];
const nestedObject = createNestedObject(keys);

console.log(nestedObject);

In the code snippet above, the `createNestedObject` function takes an array of keys as input and uses the `reduceRight` method to build the nested object from the innermost key to the outermost key. The `{ [key]: acc }` expression creates a new object with the current key as the property and the accumulator object as its value.

You can easily customize this function to handle different scenarios, such as initializing the nested object with a specific value or adding properties to the final nested object. For example, if you want to initialize the nested object with a default value, you can modify the function as follows:

Javascript

function createNestedObject(keys, value = null) {
  return keys.reduceRight((acc, key) => ({ [key]: acc }), value);
}

const keys = ['key1', 'key2', 'key3'];
const defaultValue = 0;
const nestedObject = createNestedObject(keys, defaultValue);

console.log(nestedObject);

By passing an additional `value` parameter to the `createNestedObject` function, you can initialize the nested object with the specified default value.

Using this approach, you can easily create nested objects from arrays of keys in a concise and elegant manner. This technique can be particularly useful when working with dynamic data structures or building configuration objects in your applications. Experiment with different variations of this function to suit your specific needs and make your code more readable and maintainable. Happy coding!

×