2013-07-24 51 views
0

有沒有辦法將json對象的「路徑」保存到變量?也就是說,如果我有這樣的事情:通過遞歸將嵌套的json對象路徑保存到變量

var obj = {"Mattress": { 
        "productDelivered": "Arranged by Retailer", 
        "productAge": { 
           "year": "0", 
           "month": "6" 
           } 
        } 
     }; 

如何循環並將每個關鍵節點名保存到變量?例如。 (我需要它在這種格式):牀墊[productDelivered],牀墊[productAge] [年],牀墊[productAge] [月]

我有部分在這個小提琴http://jsfiddle.net/4cEwf/,但正如你可以在日誌中看到,年和月不會分開,但也會附加到數組。我知道這是因爲我正在進行的循環,但我堅持如何進步以獲得我需要的數據格式。我在小提琴中設置的流程正在模擬我需要的東西。

有沒有一種方法我沒有考慮這樣做?

回答

1

嘗試

var obj = { 
    "Mattress": { 
     "productDelivered": "Arranged by Retailer", 
     "productAge": { 
      "year": "0", 
      "month": "6" 
     } 
    } 
}; 

var array = []; 

function process(obj, array, current){ 
    var ikey, value; 
    for(key in obj){ 
     if(obj.hasOwnProperty(key)){ 
      value = obj[key]; 
      ikey = current ? current + '[' + key + ']' : key; 
      if(typeof value == 'object'){ 
       process(value, array, ikey) 
      } else { 
       array.push(ikey) 
      } 
     } 
    } 
} 
process(obj, array, ''); 
console.log(array) 

演示:Fiddle

+0

哇!這正是我所追求的:D非常感謝你:) – user2535949

0
var obj = {"Mattress": { 
        "productDelivered": "Arranged by Retailer", 
        "productAge": { 
           "year": "0", 
           "month": "6" 
           } 
        } 
     }; 
var Mattress = new Array(); 
for(var i in obj.Mattress){ 
    if(typeof(obj.Mattress[i])==='object'){ 
     for(var j in obj.Mattress[i]){ 
      if(Mattress[i]!=undefined){ 
       Mattress[i][j] = obj.Mattress[i][j]; 
      } 
      else{ 
       Mattress[i] = new Array(); 
       Mattress[i][j] = obj.Mattress[i][j]; 
      } 
     } 
    } 
    else{ 
     Mattress[i] = obj.Mattress[i]; 
    } 
}  
for(var i in Mattress){ 
    if(typeof(Mattress[i])==='object'){ 
     for(var j in Mattress[i]){ 
      alert(j+":"+Mattress[i][j]); 
     } 
    } 
    else{ 
     alert(i+":"+Mattress[i]); 
    } 
}