Full path of a json object

前端 未结 9 778
忘了有多久
忘了有多久 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:34

    A non fancy approach, internally uses recursion.

    var x = { one:1,two:{three:3},four:{five: 5,six:{seven:7},eight:8},nine:9};
    var res = {};
    var constructResultCurry = function(src){ return constructResult(res,src); }
            
    function constructResult(target, src) {
      if(!src) return;
      target[src.key] = src.val;
    }
            
    function buildPath(key, obj, overAllKey) {
      overAllKey += (overAllKey ? "." : "") + key;
      if(typeof obj[key] != "object") return { key : overAllKey, val : obj[key] };
      Object.keys(obj[key]).forEach(function(keyInner) {
         constructResultCurry(buildPath(keyInner, obj[key], overAllKey));  
      });
    }
            
    Object.keys(x).forEach(function(k){
      constructResultCurry(buildPath(k, x, ""));
    });
    
    console.log(res);

提交回复
热议问题