遍历Parent-Child对象并使用underscore.js构造路径值

时间:2015-06-03 08:29:41

标签: javascript jquery 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'属性返回所有子元素,这些属性再次以子项目格式返回数据。基本上,如果hasChildren为true,那么该级别中有'n'个孩子。

下划线.js可以做深度监视或使用类似_.map之类的东西可以获取从父对象到所有子元素的所有路径值吗?

最后所需路径的结果是。
父/ Child1 / Child11 / Child111
父/ Child1 / Child12 / Child112
(上例中的Child1有两个子元素child11和child12)
父/ CHILD2 / Child22 / child222
父/ CHILD2 / Child22 / child333
(上例中的Child22有两个子元素child222和child333)

1 个答案:

答案 0 :(得分:0)

我正在使用这样的函数,它以递归方式构造所有键的路径。希望这有帮助

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