List all possible paths using lodash

前端 未结 6 1102
终归单人心
终归单人心 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条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-18 00:35

    Here's my solution. I only did it because I felt the other solutions used too much logic. Mine does not use lodash since I don't think it would add any value. It also doesn't make array keys look like [0].

    const getAllPaths = (() => {
        function iterate(path,current,[key,value]){
            const currentPath = [...path,key];
            if(typeof value === 'object' && value != null){
                return [
                    ...current,
                    ...iterateObject(value,currentPath) 
                ];
            }
            else {
                return [
                    ...current,
                    currentPath.join('.')
                ];
            }
        }
    
        function iterateObject(obj,path = []){
            return Object.entries(obj).reduce(
                iterate.bind(null,path),
                []
            );
        }
    
        return iterateObject;
    })();
    

    If you need one where the keys are indexed using [] then use this:

        const getAllPaths = (() => {
            function iterate(path,isArray,current,[key,value]){
                const currentPath = [...path];
                if(isArray){
                    currentPath.push(`${currentPath.pop()}[${key}]`);
                }
                else {
                    currentPath.push(key);
                }
                if(typeof value === 'object' && value != null){
                    return [
                        ...current,
                        ...iterateObject(value,currentPath) 
                    ];
                }
                else {
                    return [
                        ...current,
                        currentPath.join('.')
                    ];
                }
            }
    
            function iterateObject(obj,path = []){
                return Object.entries(obj).reduce(
                    iterate.bind(null,path,Array.isArray(obj)),
                    []
                );
            }
    
            return iterateObject;
        })();
    

提交回复
热议问题