数据源到数组的树结构格式

时间:2018-08-22 20:02:49

标签: javascript json node.js lodash

我无法进入root-> countries-> states-> citys-> zones-> campus。我只进入根国家。请帮助我完成此操作。

这是代码段,我已经用一种基本的代码方式尝试过。请帮助我完成此操作。

function getLocationsTree(locations,cb) {
var rootObj = {};
var cities = [];
var rootObj = _.where(locations, {'locationTypeId': 10000})[0];
var countries = _.where(locations, {locationTypeId: 10028, 
 parentId:rootObj.id.toString()});
var i = 0;
//var countriesData = [];
_.each(countries, function(country, index){
  i++;
  var states = _.where(locations, {locationTypeId: 10029,  parentId:country.id.toString()});
  _.each(states, function(state, index){
     cities = _.where(locations, {locationTypeId: 10030, parentId:state.id.toString()});
      //console.log("cities", cities);
      _.each(cities, function(city, index){
        console.log({locationTypeId: 10031, parentId:city.id.toString()});
      var zones = _.where(locations, {locationTypeId: 10031, parentId:city.id.toString()});
      console.log("zones", zones);
        if(zones.length > 0 ){
          _.each(zones, function(zone, index){
            var campuses = _.where(locations, {locationTypeId: 10032, parentId:zone.id.toString()});
            console.log("campus length", campuses.length);
            if(campuses.length > 0){
              zone.children = campuses;
            }
          });
          city.children = zones;
        }
      });
      console.log("cities",cities);
      states.children = cities;
  });
  country.children = states;
  if (i == countries.length){
    rootObj.children = countries;
    rootObj.childrenCount = countries.length;
    cb(null, rootObj);
  }
});

0 个答案:

没有答案
相关问题