2016-07-29 138 views
-2

由於原因,我不想深入研究在Java應用程序中運行Java jash腳本的結構,現在它具有不同的結構。由於Java團隊無法將之前已經存在的對象數組轉換成對象,因此它不會成爲對象的對象。這裏的複雜性在於它的嵌套非常像5-6層。與其使用我爲幾個應用程序進行轉換的直接方法,找到一種獲得遞歸解決方案的方法非常好。對象對象數組對象

這裏的結構是什麼樣的解決方案應該是不可知的鍵名:

{ 
    "abc": { 
    "items": { 
    "0": { 
     "cde": "123456", 
     "fgh":{ 
      "0": {"ijk":"987654"} 
     } 
    }, 

    .... 
It goes on and on. 
} 

} 
} 

對不起,我不漂亮打印JSON

產量預計:

{ 
    "abc": { 
    "items": [ 
    { 
     "cde": "123456", 
     "fgh":[{"ijk":"987654"}], 

    .... 
It goes on and on. 
    } 

] 
} 

我已經能夠使用下劃線的_.toArray和我自己的函數,因爲下劃線的解決方案是完美的克拉。

有沒有建議嗎?任何解決方案?強調?

+1

它根本不清楚你想要什麼輸出實際樣子。但它看起來像一個嵌套數組的JSON表示,看起來好像不應該太難以至少開始 - 到目前爲止你有什麼,以及它有什麼問題? –

+0

我的歉意。具有「項目」的部分:{「0」:{...}}應該是一個數組,例如「items」:[{「cde」:「123456」,...}] – nickmenow

回答

1

這會幫助你入門..請閱讀我的意見,以提高解決方案

//test object 
var json = { 
    "abc": { 
     "items": { 
      "0": { 
       "cde": "123456", 
       "fgh":{ 
        "0": {"ijk":"987654"} 
       } 
      }, 
     }, 
    }, 
}; 

//check array: this code should be customized to your needs- I only check for numbers here 
var isArray = function (obj) { 
    if (typeof obj !== 'object') 
     throw new Error('invalid argument'); 
    for (var m in obj) 
     if (obj.hasOwnProperty(m) && !/^\d+$/.test(m)) //test if key is numeric 
     return false; 

    return true; 
} 

//recursive parse-function 
var parse = function (obj, node) { 
    if (typeof obj !== 'object') 
     return obj; //break condition for non objects 

    if (isArray(obj)) { 
     node = node || []; 
     for (var m in obj) 
      node.push(parse(obj[m])); 
    } 
    else { 
     node = node || {}; 
     for (var m in obj) 
      node[m] = parse(obj[m]); 
    } 

    return node; 
} 

//run 
var newObj = parse(json); 
console.log(JSON.stringify(newObj)); 

的jsfiddle:https://jsfiddle.net/oh4ncbzc/

+0

謝謝。這完全符合我的目的。我從中學到了很多,因爲這種方法比我的嘗試更簡單,更好。 – nickmenow

+0

不客氣。 – Wolfgang