遍历父子对象并使用下划线构造路径值

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

本文关键字:路径 下划线 父子 对象 遍历      更新时间:2023-09-26

下面有一个对象

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"answers"Parent"属性返回所有子元素,该结构再次返回数据,如子项格式。基本上,如果hasChildren为真,则该级别包含'n'个子级别。

js可以做深度观察,或者使用_之类的东西。地图可以得到所有的路径值开始从父对象到所有的子元素?

所需路径的最终结果为。
父/Child1/Child11 Child111
父/Child1/Child12 Child112
(上面例子中的Child1有两个子元素child11和child12)
父/Child2/Child22 child222
父/Child2/Child22 child333
(上面例子中的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
    }
  }
}));