Full path of a json object

前端 未结 9 796
忘了有多久
忘了有多久 2021-01-12 06:02

I\'m trying to flatten an object where the keys will be the full path to the leaf node. I can recursively identify which are the leaf nodes but stuck trying to construct the

9条回答
  •  半阙折子戏
    2021-01-12 06:47

    Using newest JS features like Object spread and Object.entries it should be pretty easy:

    function flatObj(obj, path = []) {
        let output = {};
    
        Object.entries(obj).forEach(([ key, value ]) => {
            const nextPath = [ ...path, key ];
    
            if (typeof value !== 'object') {
                output[nextPath.join('.')] = value;
    
                return;
            }
    
            output = {
                ...output,
    
                ...flatObj(value, nextPath)
            };
        });
    }
    

    Please note that this code is probably not the most optimal one as it copies the object each time we want to merge it. Treat it more as a gist of what would it look like, rather than a complete and final solution.

提交回复
热议问题