【问题标题】:Javascript flatten deep nested childrenJavascript 展平深层嵌套的子级
【发布时间】:2016-08-10 16:29:01
【问题描述】:

我真的想不通这个。我正在尝试展平作为特定节点的深层子节点的 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"
}];

或视觉上:

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

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']

【问题讨论】:

  • 为什么需要递归?这是一个简单的对象数组。
  • 因为有多个级别,所以我的 parent_id 总是最接近的父级,除非我在监督什么?
  • 所以您希望所有子 ID 都从父级开始,包括该父级下的所有节点?
  • 这非常接近拓扑排序,以防您稍后使用谷歌搜索。

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


【解决方案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。

编辑:我测试了它,现在它应该可以工作了。见小偷: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;
}

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 2016-05-07
    • 2020-09-23
    • 1970-01-01
    • 2021-02-03
    • 2022-01-13
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多