Fastest way to flatten / un-flatten nested JSON objects

前端 未结 13 1502
孤城傲影
孤城傲影 2020-11-21 20:32

I threw some code together to flatten and un-flatten complex/nested JSON objects. It works, but it\'s a bit slow (triggers the \'long script\' warning).

For the flat

13条回答
  •  深忆病人
    2020-11-21 21:13

    Here's mine. It runs in <2ms in Google Apps Script on a sizable object. It uses dashes instead of dots for separators, and it doesn't handle arrays specially like in the asker's question, but this is what I wanted for my use.

    function flatten (obj) {
      var newObj = {};
      for (var key in obj) {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
          var temp = flatten(obj[key])
          for (var key2 in temp) {
            newObj[key+"-"+key2] = temp[key2];
          }
        } else {
          newObj[key] = obj[key];
        }
      }
      return newObj;
    }
    

    Example:

    var test = {
      a: 1,
      b: 2,
      c: {
        c1: 3.1,
        c2: 3.2
      },
      d: 4,
      e: {
        e1: 5.1,
        e2: 5.2,
        e3: {
          e3a: 5.31,
          e3b: 5.32
        },
        e4: 5.4
      },
      f: 6
    }
    
    Logger.log("start");
    Logger.log(JSON.stringify(flatten(test),null,2));
    Logger.log("done");
    

    Example output:

    [17-02-08 13:21:05:245 CST] start
    [17-02-08 13:21:05:246 CST] {
      "a": 1,
      "b": 2,
      "c-c1": 3.1,
      "c-c2": 3.2,
      "d": 4,
      "e-e1": 5.1,
      "e-e2": 5.2,
      "e-e3-e3a": 5.31,
      "e-e3-e3b": 5.32,
      "e-e4": 5.4,
      "f": 6
    }
    [17-02-08 13:21:05:247 CST] done
    

提交回复
热议问题