简体   繁体   English

Javascript 展平深层嵌套的子级

[英]Javascript flatten deep nested children

I really can't figure out this one.我真的想不通这个。 I'm trying to flatten the category_id that are deep child of a specific node.我正在尝试将特定节点的深层子节点的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"
}];

Or visually:或者视觉上:

在此处输入图片说明

The closest I got to was to recursively loop through the first item found:我最接近的是递归遍历找到的第一个项目:

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;
}

Current output of children(59) is ['66', '67', '68'] . children(59)当前输出是['66', '67', '68']

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

I didn't test but it should work:我没有测试,但它应该工作:

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;
}

I am using lodash.我正在使用 lodash。

Edit: I tested it and now it should work.编辑:我测试了它,现在它应该可以工作了。 See the plunker: https://plnkr.co/edit/pmENXRl0yoNnTczfbEnT?p=preview查看 plunker: https ://plnkr.co/edit/pmENXRl0yoNnTczfbEnT ? p = preview

Here is a small optimisation you can make by discarding the filtered categories.这是一个小的优化,您可以通过丢弃过滤的类别来进行。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM