List all possible paths using lodash

前端 未结 6 1060
终归单人心
终归单人心 2021-01-18 00:08

I would like to list all paths of object that lead to leafs

Example:

var obj = {
 a:\"1\",
 b:{
  foo:\"2\",
  bar:3
 },
 c:[0,1]
}

6条回答
  •  梦毁少年i
    2021-01-18 00:14

    Based on Nick answer, here is a TS / ES6 imports version of the same code

    import {isArray,flatMap,map,keys,isPlainObject,concat} from "lodash";
    
    // See https://stackoverflow.com/a/36490174/82609
    export function paths(obj: any, parentKey?: string): string[] {
      var result: string[];
      if (isArray(obj)) {
        var idx = 0;
        result = flatMap(obj, function(obj: any) {
          return paths(obj, (parentKey || '') + '[' + idx++ + ']');
        });
      } else if (isPlainObject(obj)) {
        result = flatMap(keys(obj), function(key) {
          return map(paths(obj[key], key), function(subkey) {
            return (parentKey ? parentKey + '.' : '') + subkey;
          });
        });
      } else {
        result = [];
      }
      return concat(result, parentKey || []);
    }
    

提交回复
热议问题