<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html" /> <meta name="keywords" content="数组转换成前端更容易解析的树状结构" /> <meta name="description" content="数组转换成前端更容易解析的树状结构"> <meta name="author" content="KG" /> <meta charset="utf-8"> <title>数组转换成前端更容易解析的树状结构</title> </head> <body> <script> var data = [{ ‘province‘: ‘浙江‘, ‘city‘: ‘温州‘, ‘code‘:‘10010‘ }, { ‘province‘: ‘浙江‘, ‘city‘: ‘杭州‘, ‘code‘:‘10011‘ }, { ‘province‘: ‘安徽‘, ‘city‘: ‘合肥‘, ‘code‘:‘10012‘ }, { ‘province‘: ‘安徽‘, ‘city‘: ‘马鞍山‘, ‘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>
原文地址:https://www.cnblogs.com/nimon-hugo/p/12694277.html
时间: 2024-10-10 01:08:20