List all possible paths using lodash

前端 未结 6 1119
终归单人心
终归单人心 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:22

    Here is my function. It generates all possible paths with dot notation, assuming there are no property names containing spaces

    function getAllPathes(dataObj) {
        const reducer = (aggregator, val, key) => {
            let paths = [key];
            if(_.isObject(val)) {
                paths = _.reduce(val, reducer, []);
                paths = _.map(paths, path => key + '.' + path);
            }
            aggregator.push(...paths);
            return aggregator;
        };
        const arrayIndexRegEx = /\.(\d+)/gi;
        let paths = _.reduce(dataObj, reducer, []);
        paths = _.map(paths, path => path.replace(arrayIndexRegEx, '[$1]'));
    
        return paths;
    }
    

提交回复
热议问题