1. 以前的作法
    https://codingdict.com/questions/8474

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    JSON.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
    return data;
    var result = {}, cur, prop, idx, last, temp;
    for(var p in data) {
    cur = result, prop = "", last = 0;
    do {
    idx = p.indexOf(".", last);
    temp = p.substring(last, idx !== -1 ? idx : undefined);
    cur = cur[prop] || (cur[prop] = (!isNaN(parseInt(temp)) ? [] : {}));
    prop = temp;
    last = idx + 1;
    } while(idx >= 0);
    cur[prop] = data[p];
    }
    return result[""];
    }
    JSON.flatten = function(data) {
    var result = {};
    function recurse (cur, prop) {
    if (Object(cur) !== cur) {
    result[prop] = cur;
    } else if (Array.isArray(cur)) {
    for(var i=0, l=cur.length; i<l; i++)
    recurse(cur[i], prop ? prop+"."+i : ""+i);
    if (l == 0)
    result[prop] = [];
    } else {
    var isEmpty = true;
    for (var p in cur) {
    isEmpty = false;
    recurse(cur[p], prop ? prop+"."+p : p);
    }
    if (isEmpty)
    result[prop] = {};
    }
    }
    recurse(data, "");
    return result;
    }
  2. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    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;
    }

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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");

輸出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[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
  1. 別人的解法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    /**
    * Recursively flattens a JSON object using dot notation.
    *
    * NOTE: input must be an object as described by JSON spec. Arbitrary
    * JS objects (e.g. {a: () => 42}) may result in unexpected output.
    * MOREOVER, it removes keys with empty objects/arrays as value (see
    * examples bellow).
    *
    * @example
    * // returns {a:1, 'b.0.c': 2, 'b.0.d.e': 3, 'b.1': 4}
    * flatten({a: 1, b: [{c: 2, d: {e: 3}}, 4]})
    * // returns {a:1, 'b.0.c': 2, 'b.0.d.e.0': true, 'b.0.d.e.1': false, 'b.0.d.e.2.f': 1}
    * flatten({a: 1, b: [{c: 2, d: {e: [true, false, {f: 1}]}}]})
    * // return {a: 1}
    * flatten({a: 1, b: [], c: {}})
    *
    * @param obj item to be flattened
    * @param {Array.string} [prefix=[]] chain of prefix joined with a dot and prepended to key
    * @param {Object} [current={}] result of flatten during the recursion
    *
    * @see https://docs.mongodb.com/manual/core/document/#dot-notation
    */
    function flatten (obj, prefix, current) {
    prefix = prefix || []
    current = current || {}

    // Remember kids, null is also an object!
    if (typeof (obj) === 'object' && obj !== null) {
    Object.keys(obj).forEach(key => {
    this.flatten(obj[key], prefix.concat(key), current)
    })
    } else {
    current[prefix.join('.')] = obj
    }

    return current
    }

https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects


Comment