Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a nested object given an array of keys

Tags:

Given is an array like this:

var level = ["a", "b", "x"]; 

The output should be:

{     "a": {         "b": {             "x": {             }         }     } } 

I tried this:

var level = ["a", "b", "x"]; var o = {}; for (var c = 0, len = level.length; c < len; c +=1 ) {      var part = level[c];      o[part] = {}; // how to remember the last part? } 

How can I remember the last part and add the next level?

like image 707
pumi Avatar asked May 11 '18 07:05

pumi


People also ask

How do I make a nested array?

Creating a Nested Array: This one is just equating the variable to the array. Second one is using the array method new Array() . And the last one is using the Array() which is similar to the new Array() . Note that all these methods yield the same result.

How do I create a nested object in JavaScript?

const obj = { code: "AA", sub: { code: "BB", sub: { code: "CC", sub: { code: "DD", sub: { code: "EE", sub: {} } } } } }; Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple. We can solve this problem using a recursive approach.

Can object keys be arrays?

Description. Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.


2 Answers

You can use reduceRight method by passing an arrow function as argument.

var level = ["a", "b", "x"];  let result = level.reduceRight((obj, elem) => ({[elem]: obj}), {});  console.log(result);
like image 79
Mihai Alexandru-Ionut Avatar answered Oct 07 '22 02:10

Mihai Alexandru-Ionut


Simplest tweak would be to reassign o on each iteration:

var level = ["a", "b", "x"];  var o = {};  var initialO = o;  for (var c = 0, len = level.length; c < len; c +=1 ) {     var part = level[c];    o[part] = {};    o = o[part];  }  console.log(initialO);

This might be a clearer way of doing it, though:

const level = ["a", "b", "x"];  const result = {};  level.reduce((accum, key) => {    accum[key] = {};    return accum[key];  }, result);  console.log(result);
like image 28
CertainPerformance Avatar answered Oct 07 '22 01:10

CertainPerformance