2013-01-31 34 views
0
構建對象

我所擁有的是一個這樣的數組:['foo','bar'],我希望把它變成一個對象,它看起來像這樣:從陣列中的JavaScript

 
{ 
    foo:{ 
      bar:{ 
       etc:{} 
      } 
    } 
} 

我已經試過兩個循環,但我如果數組中有三個值,可以使其工作。

+1

你想要什麼它看起來像在數組中的三個值? – Shmiddty

+1

那麼告訴我們你試過了什麼。 – gdoron

+0

總會有兩個值嗎?如果不是,應該是什麼樣子? – Danny

回答

5
var obj = {}; 
var pointer = obj; 

array.forEach(function (item) { 
    pointer = pointer[item] = {}; 
}); 

這裏的小提琴:http://jsfiddle.net/h67ts/


如果您有支持IE < 9,您既可以使用常規的循環,或使用this polyfill

if (!Array.prototype.forEach) { 
    Array.prototype.forEach = function(fn, scope) { 
    for(var i = 0, len = this.length; i < len; ++i) { 
     fn.call(scope, this[i], i, this); 
    } 
    } 
} 
+0

IE說他不喜歡'forEach'。 –

+0

非常感謝。 – locrizak