2014-09-23 59 views
1

本質上,我試圖初始化一個JavaScript對象,並讓它包含具有單個鍵的空對象。例如:將JavaScript對象「樹」初始化爲任意深度,嵌套對象

getOject('one.two.three') 

會導致對象:

{one:{two:{three:''}}} 

據我所知,你不能用動態密鑰名稱初始化,除非你使用數組表示法

root[dynamicKey] = 'some variable'; 

所以我需要循環遍歷並根據參數的數量初始化每個參數,然後賦值它的值,但語法似乎並沒有讓我以我所知的任何方式進行操作。

因此,如果沒有一個循環,將是這樣的:

jsonifiedForm[rootKey] = {}; 
jsonifiedForm[rootKey][childKeys[0]] = {}; 
jsonifiedForm[rootKey][childKeys[0]][childKeys[1]] = $input.val(); 

我不能想辦法做到這一點,我不是典型的是JS傢伙,所以它可能是簡單的東西但我在Google上找不到任何東西或堆棧溢出

先謝謝您!

+1

'jsonifiedForm [rootKey] = {[childKeys [0]]:{[childKeys [1]]:$ input.val()}}'在ES6中有效。在此之前,假設你爲瀏覽器編寫了一個你認爲最好的代碼(假設你正在循環它)。 – 2014-09-23 22:23:50

+0

爲什麼選擇投票? – njfife 2014-09-23 22:33:26

回答

5

這個函數應該是你要找的。

function getOject(str) { 
    // this turns the string into an array = 'one.two.three' becomes ['one', 'two', 'three'] 
    var arr = str.split('.'); 

    // this will be our final object 
    var obj = {}; 

    // this is the current level of the object - in the first iteration we will add the "one" object here 
    var curobj = obj; 

    var i = 0; 
    // we loop until the next-to-last element because we want the last element ("three") to contain an empty string instead of an empty object 
    while (i < (arr.length-1)) { 
     // add a new level to the object and set the curobj to the new level 
     curobj[arr[i]] = {}; 
     curobj = curobj[arr[i++]]; 
    } 
    // finally, we append the empty string to the final object 
    curobj[arr[i]] = ''; 
    return obj; 
} 
+0

好吧,非常酷,你自己寫了嗎?只是想確保作者得到信用=) – njfife 2014-09-23 22:32:10

+1

請解釋事情是如何工作的,而不是隻是轉儲你寫的代碼,它可以幫助更多。 – 2014-09-23 22:34:40

+0

我認爲他認爲這很清楚。它很清楚它在做什麼(對我來說至少)解釋總是不錯,雖然 – njfife 2014-09-23 22:36:16

3

因爲JavaScript中的變量,而不是引用它們複製「到」變量值,我們可以讓我們的初始值,然後作出它的一個引用正如我們在深入研究下來,我們會左右移動:

var getOject = function (k, s) { 
     // initialize our value for return 
    var o = {}, 
     // get a reference to that object 
     r = o, 
     i; 

    // we'll allow for a string or an array to be passed as keys, 
    //and an optional sepeartor which we'll default to `.` if not given 
    if (typeof k === 'string') { 
     k = k.split(s || '.'); 
    } 

    // do we have an array now? 
    if (k && k.length) { 
     //iterate it 
     for (i = 0; i < k.length; i += 1) { 
      // set a property on the referenced object 
      r[k[i]] = {}; 
      // point the reference to the new level 
      r = r[k[i]]; 
     } 
    } 

    // send back the object 
    return o; 
} 

console.log(getOject('one.two.three')); 
console.log(getOject('four|five|six', '|')); 

r指向同一件事,o的確,最初,當我們移動參考(r)深入o和寫入,我們建立了o,因爲我們去。

末輸出兩個console.log()調用以下:

first log output second log output

還要注意,我讓你在一個數組下手,如果你覺得它傳遞,並提出了分離器的參數所以你沒有被卡住.

+0

這也非常出色,我認爲我現在將繼續我的第一選擇,現在他解釋了它,它恰好與我在操作中所說的內容完全吻合。 – njfife 2014-09-23 22:42:31

+0

瞭解了,他的回答是正確的,並且在我之前。 :) – JAAulde 2014-09-23 22:43:10