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?
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.
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With