基于数组生成的递归对象

Ben*_*wis 3 javascript

我有一个数组,这是一个键列表:['one', 'two', 'three'].

我需要生成一个以下格式的对象:

{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试了几种方法,但它们看起来很混乱(我有一种方法可以使用,while(current = array.pop())但它需要几个条件来处理第一个和最后一个元素.

有一个更整洁的递归策略吗?

Nen*_*car 6

您可以使用reduce()方法和要添加属性的累加器传递对象.

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 Code Online (Sandbox Code Playgroud)

如果你想只使用没有循环的递归,你可以创建这样的函数.

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 Code Online (Sandbox Code Playgroud)