2016-02-26 80 views
-1

我有以下嵌套的json列表。 我有loopJson實現,但它不是遞歸的,它不傳遞第一個對象列表。如果有人可以建議遞歸調用應該做的地方,那麼它將會很好,所以它會執行遞歸。拆分單獨的json到單獨的列表

{ 
"key": "math", 
"right": { 
    "key": "Math" 
}, 
"left": { 
    "key": "A Greek–English Lexicon", 
    "right": { 
     "key": "A-list" 
    }, 
    "left": { 
     "key": "ASCII" 
    } 
} 
} 

     var loopJson = function(json){ 

     if(json.left.key != null){ 
      that.arrayTest.push({key:json.key,left:json.left.key}); 
     } 
     if(json.right.key != null){ 
      that.arrayTest.push({key:json.key,right:json.right.key}); 
     } 
    } 

的目標是: 迭代通過各對象,並創建對象的數組包括與鍵(「鑰匙」,「右」)或(「鑰匙」,「左」)的對象。由於當前的json是嵌套的,我想將json拆分成一個對象數組。但是,它不會迭代每個對象,因爲它不是遞歸的。我不得不找到一種方法使其遞歸。

預期輸出的一個例子:

[{key:"math",right:"Math"},{key:"math",left: "A Greek–English Lexicon"},{key: "A Greek–English Lexicon",left:""ASCII},{key: "A Greek–English Lexicon",right:"A-list"}] 
+1

的功能是什麼目的?或者更好的你喜歡做什麼? –

回答

1

var input = { 
 
    "key": "math", 
 
    "right": { 
 
     "key": "Math" 
 
    }, 
 
    "left": { 
 
     "key": "A Greek–English Lexicon", 
 
     "right": { 
 
      "key": "A-list" 
 
     }, 
 
     "left": { 
 
      "key": "ASCII" 
 
     } 
 
    } 
 
}; 
 

 
var nestedMethod = function(input) { 
 
    var output = []; 
 
    
 
    if (input.right) { 
 
    output.push({ key: input.key, right: input.right.key }); 
 
    output = output.concat(nestedMethod(input.right)); 
 
    } 
 
    
 
    if (input.left) { 
 
    output.push({ key: input.key, left: input.left.key }); 
 
    output = output.concat(nestedMethod(input.left)); 
 
    } 
 
    
 
    return output; 
 
} 
 

 
document.write(JSON.stringify(nestedMethod(input)));

1

這是一個遞歸函數和屬性的固定陣列的提案,看管。

var object = { 
 
     "key": "math", 
 
     "right": { 
 
      "key": "Math" 
 
     }, 
 
     "left": { 
 
      "key": "A Greek–English Lexicon", 
 
      "right": { 
 
       "key": "A-list" 
 
      }, 
 
      "left": { 
 
       "key": "ASCII" 
 
      } 
 
     } 
 
    }, 
 
    array = []; 
 

 
function getParts(object, array) { 
 
    ['right', 'left'].forEach(function (k) { 
 
     var o; 
 
     if (object[k]) { 
 
      o = { key: object.key }; 
 
      o[k] = object[k].key; 
 
      array.push(o); 
 
      getParts(object[k], array); 
 
     } 
 
    }); 
 
} 
 

 
getParts(object, array); 
 
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');