-1

I'd like to restructure some JSON data into a different format, for convenience. The format in which I get it from the server is inconvenient for me; all of the items are in one node, but some of them have parent: id which tells us the parent for that item.

I'd like to take the JSON structure from JsonFromSrver and restructure to look like resultJson. I also need to be able to send the data back to the server in the original format after making modifications.

var JsonFromSrver = [
        {
            "id": 1,
            "type": "folder",
            "title": "HeadItem1",
        },
        {
            "id": 2,
            "type": "folder",
            "title": "HeadItem2",
        },
        {
            "id": 33,
            "parent": 1,
            "type": "file",
            "title": "ChildItem",

        },
        {
            "id": 103,
            "parent": 2,
            "type": "file",
            "title": "ChildItem"
        }
]

var resultJson = [
        {
            "id": 1,
            "type": "folder",
            "title": "HeadItem1",
            "children": 
               [{
                  "id": 33,
                  "parent": 1,
                  "type": "file",
                  "title": "ChildItem"
              }]
        },
        {
            "id": 2,
            "type": "folder",
            "title": "HeadItem2",
            "children": 
               [{
                  "id": 103,
                  "parent": 2,
                  "type": "file",
                  "title": "ChildItem"
              }]
        }
]

1 Answers1

1

I'd simply collect the data into the hierarchical object structure and then stringify:

var result = {};

for (var j in JsonFromSrver) {
    var obj = JsonFromSrver[j];
    if (!obj.parent) {
        result[obj.id] = obj;
        continue;
    }
    var parentObj = result[obj.parent];
    if (!parentObj.children) parentObj.children = [];   
    parentObj.children.push(obj);   
}

resultJson = [];
for (var i in result) {
    resultJson.push(result[i]);
}


console.log(JSON.stringify(resultJson));