Javascript压扁深嵌套的孩子

时间:2016-04-18 19:09:34

标签: javascript arrays object while-loop nested-loops

我真的无法弄清楚这个。我正在尝试压缩特定节点的深层子category_id

var categories = [{
  "category_id": "66",
  "parent_id": "59"
}, {
  "category_id": "68",
  "parent_id": "67",
}, {
  "category_id": "69",
  "parent_id": "59"
}, {
  "category_id": "59",
  "parent_id": "0",
}, {
  "category_id": "67",
  "parent_id": "66"
}, {
  "category_id": "69",
  "parent_id": "59"
}];

或视觉上:

enter image description here

我最接近的是递归遍历找到的第一个项目:

function children(category) {
    var children = [];
    var getChild = function(curr_id) {
        // how can I handle all of the cats, and not only the first one?
        return _.first(_.filter(categories, {
            'parent_id': String(curr_id)
        }));
    };

    var curr = category.category_id;

    while (getChild(curr)) {
        var child = getChild(curr).category_id;
        children.push(child);
        curr = child;
    }

    return children;
}

children(59)的当前输出为['66', '67', '68']

预期输出为['66', '67', '68', '69']

1 个答案:

答案 0 :(得分:1)

我没有测试,但应该可以工作:

function getChildren(id, categories) {
  var children = [];
  _.filter(categories, function(c) {
    return c["parent_id"] === id;
  }).forEach(function(c) {
    children.push(c);
    children = children.concat(getChildren(c.category_id, categories));
  })

  return children;
}

我正在使用lodash。

编辑:我测试了它,现在它应该工作。请参阅plunker:https://plnkr.co/edit/pmENXRl0yoNnTczfbEnT?p=preview

您可以通过丢弃已过滤的类别进行小规模优化。

function getChildren(id, categories) {
  var children = [];
  var notMatching = [];
  _.filter(categories, function(c) {
    if(c["parent_id"] === id)
      return true;
    else
      notMatching.push(c);
  }).forEach(function(c) {
    children.push(c);
    children = children.concat(getChildren(c.category_id, notMatching));
  })

  return children;
}