This question already has answers here:
Create a dynamic nested object from array of properties
                                
                                    (4个答案)
                                
                        
                                5年前关闭。
            
                    
我需要从数组创建一个对象。

例如,

我有一个像var arr = ['a', 'b', 'c'];这样的数组

它应该转换为

{
  a:{
    b:{
      c:{

      }
    }
  }
}


我尝试了以下代码,但无法创建深树,

var arr = ['a', 'b', 'c'];
var obj = {},
    temp = 'asd';
for(var i=0; i<arr.length; i++){
    if($.isEmptyObject(obj)){
        obj[arr[i]] = {};
    } else {
        console.log(Object.keys(obj));
        obj[Object.keys(obj)][arr[i]] = {};
    }
}
console.log(obj, temp);


Fiddle

有人能帮我吗?

提前致谢。

最佳答案

您可以尝试类似



var arr = ['a', 'b', 'c'];
var obj = temp = {};
for (var i = 0; i < arr.length; i++) {
  temp = temp[arr[i]] = {}
}

$('#result').html(JSON.stringify(obj))

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>

关于javascript - Javascript-从数组创建深层对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26929168/

10-12 12:55
查看更多