Generated recursive array based object

I have an array, which is a list of keys: ['one', 'two', 'three']

.

I need to generate an object of the following format:

{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}

      

I have tried several approaches so far, but they seem to be quite messy (I have one method that uses while(current = array.pop())

, but it takes multiple conditionals to handle the first and last items.

Is there a neater recursive strategy?

+3


source to share


4 answers


You can use the method reduce()

and as an accumulator skip object to which you want to add properties.

var arr = ['one', 'two', 'three']
var obj = {}

arr.reduce(function(r, e, i) {
  r.path = e;
  return arr[i+1] ? r.nested = {} : r
}, obj)

console.log(obj)
      

Run codeHide result




If you only want to use recursion without a loop, you can create a function like this.

var data = ['one', 'two', 'three']
var obj = {}

function makeObj(arr, n, o) {
  if (n == arr.length - 1) o.path = arr[n]
  else {
    o.path = arr[n];
    o.nested = {}
    makeObj(arr, n += 1, o.nested)
  }
  return o.nested
}

makeObj(data, 0, obj)
console.log(obj)
      

Run codeHide result


+6


source


var arr = ['one', 'two', 'three'];
var tree = arr.reduceRight((nested, path) => {
  return nested? {path, nested}: {path};
}, null);

console.log(tree);
      

Run codeHide result


or even better / simpler, just:



var arr = ['one', 'two', 'three'];
var tree = arr.reduceRight((nested, path) => ({path, nested}), null);

console.log(tree);
      

Run codeHide result


This simplifies things for the JS engine if all objects have the same hidden class (simplified: same property names).

+2


source


let arr = ['one', 'two', 'three'], obj = {};

obj['path'] = arr[arr.length - 1];
for(let i = arr.length - 2; i >= 0; i--) {
  obj = {
    path: arr[i],
    nested: obj
  };
}
console.log(obj);

      

0


source


To solve this problem, you can use a decrement for

:

var props = ['one','two','three'],
    obj;
    
for(var a = props.length;a--;) {
    var temp = { path: props[a] };
    if(obj) {
        temp.nested = obj;
    }
    obj = temp;
}

console.log(obj);
      

Run codeHide result


0


source







All Articles