JavaScript build nested array from string values

后端 未结 1 522
爱一瞬间的悲伤
爱一瞬间的悲伤 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; i0)
            obje = obje.addChild(arr);
    }
    
    
    var finArr = [];
    for(i=0; i0)
                    recc.addChildren(nested[i]);
            finArr.push(recc);        
        }
    }
    
    console.log('------------------------------------------')
    console.log(JSON.stringify(finArr));
    console.log('--------------------The End---------------')
    

    0 讨论(0)
提交回复
热议问题