2015-10-07 63 views
1

我想按照以下方式重構JSON數組。在輸出中,我需要id作爲鍵和對象本身作爲它的值。重組JSON數組

樣品輸入:

[ 
    { 
     "id": "1", 
     "children": [ 
      { 
       "id": "1-1", 
       "children": [ 
        { 
         "id": "1-1-1", 
         "children": [] 
        }, 
        { 
         "id": "1-1-2", 
         "children": [] 
        } 
       ] 
      }, 
      { 
       "id": "1-2", 
       "children": [] 
      } 
     ] 
    }, 
    { 
     "id": "2", 
     "children": [] 
    }, 
    { 
     "id": "3", 
     "children": [ 
      { 
       "id": "3-1", 
       "children": [] 
      } 
     ] 
    } 
] 

需要的輸出:

{ 
    "1": { 
     "id": "1", 
     "children": { 
      "1-1": { 
       "id": "1-1", 
       "children": { 
        "1-1-1": { 
         "id": "1-1-1", 
         "children": [] 
        }, 
        "1-1-2": { 
         "id": "1-1-2", 
         "children": [] 
        } 
       } 
      }, 
      "1-2": { 
       "id": "1-2", 
       "children": [] 
      } 
     } 
    }, 
    "2": { 
     "id": "2", 
     "children": [] 
    }, 
    "3": { 
     "id": "3", 
     "children": { 
      "3-1": { 
       "id": "3-1", 
       "children": [] 
      } 
     } 
    } 
} 

下面的代碼讓我幾乎所需答案。

function restruct(arr) { 
    var newArray = arr.map(function(obj) { 
     var t = {}; 
     if (obj.children) 
      obj.children = restruct(obj.children); 
     t[obj.id] = obj; 
     return t; 
    }); 
    return newArray; 
} 

輸出是:

[ 
    { 
     "1": { 
      "id": "1", 
      "children": [ 
       { 
        "1-1": { 
         "id": "1-1", 
         "children": [ 
          { 
           "1-1-1": { 
            "id": "1-1-1", 
            "children": [] 
           } 
          }, 
          { 
           "1-1-2": { 
            "id": "1-1-2", 
            "children": [] 
           } 
          } 
         ] 
        } 
       }, 
       { 
        "1-2": { 
         "id": "1-2", 
         "children": [] 
        } 
       } 
      ] 
     } 
    }, 
    { 
     "2": { 
      "id": "2", 
      "children": [] 
     } 
    }, 
    { 
     "3": { 
      "id": "3", 
      "children": [ 
       { 
        "3-1": { 
         "id": "3-1", 
         "children": [] 
        } 
       } 
      ] 
     } 
    } 
] 

如果您發現,一切都按照預期的輸出除了children節點。它返回對象數組,而我需要使用鍵值對的對象。任何人都可以幫助我嗎?

+3

好奇什麼是錯的或有問題的,使用目前的結構?看起來代碼更友好 – charlietfl

+0

@charlietfl,我使用的JavaScript庫需要上述格式作爲輸入。 – PrashantJ

回答

3

不能使用map因爲它返回一個數組,你可以使用forEach代替,如:

function restruct(arr) { 
    var result = {}; 

    arr.forEach(function(obj) {   
     if (obj.children) { 
      obj.children = restruct(obj.children); 
     } 

     result[obj.id] = obj; 
    }); 
    return result; 
}