我真的不知道这个。我正在尝试展平属于特定节点的子级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"
}];


或视觉上:

javascript - Javascript扁平化深层嵌套的子级-LMLPHP

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

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

最佳答案

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

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

关于javascript - Javascript扁平化深层嵌套的子级,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36702379/

10-08 22:04