簡體   English   中英

Javascript 展平深層嵌套的子級

[英]Javascript flatten deep nested children

我真的想不通這個。 我正在嘗試將特定節點的深層子節點的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']

我沒有測試,但它應該工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM