簡體   English   中英

遍歷Parent-Child對象並使用underscore.js構造路徑值

[英]traverse through Parent-Child objects and construct path value using underscore.js

我有下面的對象

var childitems = function(child) {
    return {
        id: item.id,
        type: child.type,
        path: child.title,
        parent: child.parent,
        hasChildren: true | false (based on some condition)
    };
};

同樣,我有一個函數,它從上述對象結構中返回基於'hasChildren'和'Parent'屬性的所有子元素,並再次以childitems格式返回數據。 基本上,如果hasChildren為true,則該級別中有n個孩子。

Underscore.js可以進行深入監視還是使用_.map之類的東西可以獲取從父對象到所有子元素的所有路徑值?

最后所需路徑的結果是。
父母/孩子1 /孩子11 /孩子111
父母/孩子1 /孩子12 /孩子112
(以上示例中的Child1具有兩個子元素child11和child12)
父母/孩子2 /孩子22 /孩子222
父母/孩子2 /孩子22 /孩子333
(以上示例中的Child22具有兩個子元素child222和child333)

我正在使用這樣的函數,它以遞歸方式構造所有鍵的路徑。 希望這可以幫助

var getKeysFlat = function(obj) {
  /* helper function to get keys of the object recursively,
     e. g {foo: 42, bar {foo: 42}} will have following keys:
     ['foo', 'bar/foo']
   */
  var result = [];
  var recurse = function (obj, keyPrefix) {
    if (keyPrefix !== ''){
      keyPrefix = keyPrefix + '/';
    }
    _.each(obj, function (val, key){
      if (_.isObject(val)){
        recurse(val, keyPrefix + key);
      } else {
        result.push(keyPrefix + key);
      }
    });
  };
  recurse(obj, '');
  return result;
};

console.log(getKeysFlat({
  value: 2, 
  child1: {
    child11: 3
  },
  child2: {
    child22: {
      child222: 4
    }
  }
}));

暫無
暫無

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

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