복붙노트

[JQUERY] jQuery로 계층 JSON으로 구분 된 문자열로 변환

JQUERY

jQuery로 계층 JSON으로 구분 된 문자열로 변환

해결법


  1. 1.

    var input = ["Fred-Jim-Bob", "Fred-Jim", "Fred-Thomas-Rob", "Fred"];
    var output = [];
    for (var i = 0; i < input.length; i++) {
        var chain = input[i].split("-");
        var currentNode = output;
        for (var j = 0; j < chain.length; j++) {
            var wantedNode = chain[j];
            var lastNode = currentNode;
            for (var k = 0; k < currentNode.length; k++) {
                if (currentNode[k].name == wantedNode) {
                    currentNode = currentNode[k].children;
                    break;
                }
            }
            // If we couldn't find an item in this list of children
            // that has the right name, create one:
            if (lastNode == currentNode) {
                var newNode = currentNode[k] = {name: wantedNode, children: []};
                currentNode = newNode.children;
            }
        }
    }
    

    출력 JSONifies로서 :

    [{
        "name": "Fred",
        "children": [{
            "name": "Jim",
            "children": [{
                "name": "Bob",
                "children": []
            }]
        }, {
            "name": "Thomas",
            "children": [{
                "name": "Rob",
                "children": []
            }]
        }]
    }]
    
  2. from https://stackoverflow.com/questions/6232753/convert-delimited-string-into-hierarchical-json-with-jquery by cc-by-sa and MIT license