2015-11-07 43 views
0

我有一個JSON配置文件如下:的JavaScript(Node.js的) - JSON遞歸與順序提取對象陣列(faltten)

var conf = [ 
    { 
     "value": "baz", 
     "threshold": 20, 
     "other": 123 
    }, 
    { 
     "value": "mo", 
     "other": 456, 
     "child": { 
      "value": "foo", 
      "other": 789, 
      "child": { 
       "value": "larry", 
       "other": 123 
      } 
     } 
    } 
]; 

我有一個要求,以提取每個對象的和他們堅持如果他們有孩子對象,一起按順序。例如,對象1(baz)是獨立的。對象2(mo)將有兩個子對象。這3個作爲一個集合必須一起提取。

子對象的數量沒有限制。

我試圖持續使用數組維持每個對象的順序。因此,所需的輸出看起來像:

[[{"value":"baz","threshold":20,"other":123}], 
[[{"value":"mo","other":456,"child":{"value":"foo","other":789,"child":{"value":"larry","other":123}}}], 
[{"value":"foo","other":789,"child":{"value":"larry","other":123}}], 
[{"value":"larry","other":123}]]] 

最後一個要求是實際從父母刪除子值,從而輸出實際上是這樣的:

[ 
    [{"value":"baz","threshold":20,"other":123}], 
    [ 
     [{"value":"mo","other":456}], 
     [{"value":"foo","other":789}], 
     [{"value":"larry","other":123}] 
    ] 
    ] 

我一直掛在這對幾乎沒有進展。我知道我需要創建一個遞歸函數,將每個節點推送到一個數組,然後檢查子對象並重復。

繼承人我到目前爲止。我的想法是,如果我可以接受每個任務被推送到的數組ID(使用循環ID),也許我可以再次調用函數時映射它。

欣賞任何指導。

var execSets = []; 功能分析器(任務){

// an ordered array of task execution 

for (let eachTask in tasks) { 
    var taskSet = []; 
    console.log("===================================="); 
    console.log(tasks[eachTask]); 

    if(!tasks[eachTask].child && typeof(tasks[eachTask]) === 'object'){ 

     console.log(tasks[eachTask]); 
     taskSet.push(tasks[eachTask]); 
     execSets.push(taskSet); 

    } 

    if(tasks[eachTask].child){ 

     let childAlias = tasks[eachTask].child; 
     delete tasks[eachTask].child; 
     taskSet.push(tasks[eachTask]); 

     execSets.push(taskSet); 
     parser(childAlias); 

    } 
} 

}

回答

0

故宮註冊表是你的朋友;嘗試'npm搜索單位,

有幾個模塊可以幫助扁平一個json對象。例如https://www.npmjs.com/package/flat

+0

平是理想的 - 非常感謝指針! – Ben

+0

沒問題,有時使用現有的解決方案是最好的 –

0

您可以使用遞歸來做到這一點。這裏是我的建議:

var conf = [ 
{ 
    "value": "baz", 
    "threshold": 20, 
    "other": 123 
}, 
{ 
    "value": "mo", 
    "other": 456, 
    "child": { 
     "value": "foo", 
     "other": 789, 
     "child": { 
      "value": "larry", 
      "other": 123 
     } 
    } 
} 
]; 


function getFlattenedObject(object){ 

    var response = []; 
    flatten(object, response, 0);  
    return response; 

} 


function flatten(object, array, index){ 

    if(!array[index]){ 
     array.push([]); 
    } 

    array[index].push(object); 

    if(object.child){ 
     flatten(object.child, array, index + 1); 
     object.child = undefined; 
    }  
} 

//Logs for comparison 
console.dir(conf) 
console.dir(getFlattenedObject(conf)); 
+0

非常感謝這個例子 - 非常有幫助。 – Ben