在Javascript对象中进行后序深度搜索

时间:2017-04-22 05:26:11

标签: javascript jquery depth-first-search

如果我有一个如下所示的对象:

var data = { pages: [{ key: 1, pages: [{ key: 2, pages: [{ key: 3 }] }, { key: 4, pages: [{ key: 5 }] }] }] };

结果数组应为:[3,5,2,4,1]

1 个答案:

答案 0 :(得分:0)

var data = {
  pages: [{
    key: 1,
    pages: [{
      key: 2,
      pages: [{
        key: 3
      }]
    }, {
      key: 4,
      pages: [{
        key: 5
      }]
    }]
  }]
};

var postOrderObj = {};

function getLevels(data) {

  for (var i = 0; i < data.pages.length; i++) {
    var obj = data.pages[i];

    if (postOrderObj[data.level]) {
      postOrderObj[data.level].push(obj.key);

      if (obj.pages) {
        getLevels({
          pages: obj.pages,
          level: data.level + 1,
          parentLevel: data.level
        });
      }
    } else {
      if (data.parentLevel) {
        data.level = data.parentLevel + 1;
      } else {
        data.parentLevel = 0;
        data.level = data.parentLevel + 1;
      }

      postOrderObj[data.level] = [obj.key];

      if (obj.pages) {
        getLevels({
          pages: obj.pages,
          level: data.level + 1,
          parentLevel: data.level
        });
      }
    }
  }
}

function getPostOrder(postOrderObj) {
  var postOrderArry = [];
  for (var key in postOrderObj) {
    var levelArry = postOrderObj[key];
    for (var i = levelArry.length - 1; i >= 0; i--) {
      postOrderArry.unshift(levelArry[i]);
    }
  }
  return postOrderArry;
}

getLevels(data);
var result = getPostOrder(postOrderObj);
console.log(result);