Full path of a json object

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

    You can achieve it by using this function:

    const obj = {
      one: 1,
      two: {
        three: 3
      },
      four: {
        five: 5,
        six: {
          seven: 7
        },
        eight: 8
      },
      nine: 9
    }
    
    
    const flatObject = (obj, keyPrefix = null) =>
      Object.entries(obj).reduce((acc, [key, val]) => {
        const nextKey = keyPrefix ? `${keyPrefix}.${key}` : key
    
        if (typeof val !== "object") {
          return {
            ...acc,
            [nextKey]: val
          };
        } else {
          return {
            ...acc,
            ...flatObject(val, nextKey)
          };
        }
    
      }, {});
      
      console.log(flatObject(obj))

提交回复
热议问题