JavaScript build nested array from string values

后端 未结 1 521
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-16 06:49

From my data source I am getting values like;

USA        |Arizona
USA        |Florida
UK         |England |Northamptonshire
UK         |England |Derbyshire
U         


        
相关标签:
1条回答
  • 2021-01-16 07:17

    Turn it to JSON:

    var str = '"USA|Arizona","USA|Florida","UK|LonelyIsland","UK|England|Northamptonshire","UK|England|Derbyshire","UK|Wales|Powys","UK|England|London|Soho","Switzerland|Lucern';
    
    var jsonStr = "[[" + str.replace(/,/g,'],[') + "\"]]";
    jsonStr = jsonStr.replace(/\|/g,'","');
    var nested = JSON.parse(jsonStr);
    

    Then play with parents and children.

    function findObject(array, key, value) {
        for (var i=0; i<array.length; i++) {
            if (array[i][key] === value) {
                return array[i];
            }
        }
        return null;
    }
    
    function obj(arr){
        this.title = arr.shift();
    }
    
    obj.prototype.addChild = function(arr){
        var tmp = new obj(arr);
        if(typeof this.children === 'undefined'){
            this.children = new Array();
            result = this.children[this.children.push(tmp)-1];
        }else{
            result = findObject(this.children, 'title', tmp.title);
            if(!result)
                result = this.children[this.children.push(tmp)-1];
        }
        return result;
    }
    
    obj.prototype.addChildren = function(arr){
        var obje = this;
        while(arr.length>0)
            obje = obje.addChild(arr);
    }
    
    
    var finArr = [];
    for(i=0; i<nested.length; i++){
        var recc = new obj(nested[i]);
        if(oldObj = findObject(finArr, 'title', recc.title)){
            oldObj.addChildren(nested[i]);
        }else{
            if(nested[i].length>0)
                    recc.addChildren(nested[i]);
            finArr.push(recc);        
        }
    }
    
    console.log('------------------------------------------')
    console.log(JSON.stringify(finArr));
    console.log('--------------------The End---------------')
    
    0 讨论(0)
提交回复
热议问题