js a daily change (the array is converted into a tree structure that is easier to parse at the front end)

<! DOCTYPE html> 
<html> 
    <head> 
        <meta http-equiv = " content-type " content = " text / html " /> 
        <meta name = " keywords " content = "The array is converted into a tree that is easier to parse at the front end Like structure " /> 
        <meta name = " description " content = " The array is converted into a tree structure that is easier to parse at the front end " > 
        <meta name = " author " content = " KG " />
        <meta charset="utf-8"> 
        <title> The array is converted into a tree structure that is easier to parse at the front end </ title> 
    </ head> 
    <body> 
        <script> var data = [{
                 ' province ' : ' Zhejiang ' ,
                 ' city ' : ' Wenzhou ' ,
                 ' code ' : ' 10010 ' 
            }, { ' province ' : ' Zhejiang ' ,
                 ' city ': ' Hangzhou
            
                ' ,
                 ' code ' : ' 10011 ' 
            }, { 
                ' province ' : ' Anhui ' ,
                 ' city ' : ' Hefei ' ,
                 ' code ' : ' 10012 ' 
            }, { 
                ' province ' : ' Anhui ' ,
                 ' city ' : 'Ma'anshan ' ,
                'code':'10013'
            }, {
                'province': '浙江',
                'city': '宁波',
                'code':'10014'
            }];

            function toTree(data) {
                var newData=[],
                hash={};
                for(var i=0;i<data.length;i++){
                    if(!hash[data[i].province]){
                        hash[data[i].province]={
                            'province':data[i].province    
                        };
                        hash[data[i].province]['city']=[{
                            'name':data[i].city,
                            'code':data[i].code
                        }];
                        newData.push(hash[data[i].province]);
                    }else if(hash[data[i].province].province==data[i].province){
                        hash[data[i].province]['city'].push({
                            'name':data[i].city,
                            'code':data[i].code
                        })
                    }
                }
                return newData;
            }
            
            console.log(toTree(data));
        </script>
    </body>
</html>

 

Guess you like

Origin www.cnblogs.com/nimon-hugo/p/12694277.html