我将一些代码放在一起,以平抑和反平抑复杂/嵌套的JavaScript对象。它可以工作,但有点慢(触发“长脚本”警告)。

对于扁平的名称,我希望用“.”作为分隔符,用[INDEX]作为数组。

例子:

un-flattened | flattened
---------------------------
{foo:{bar:false}} => {"foo.bar":false}
{a:[{b:["c","d"]}]} => {"a[0].b[0]":"c","a[0].b[1]":"d"}
[1,[2,[3,4],5],6] => {"[0]":1,"[1].[0]":2,"[1].[1].[0]":3,"[1].[1].[1]":4,"[1].[2]":5,"[2]":6}

我创建了一个基准测试,用于模拟我的用例http://jsfiddle.net/WSzec/

获得一个嵌套对象 压平它 查看它,并可能修改它,而扁平 将其平放回原始的嵌套格式,然后运走

我想要更快的代码:为了澄清,代码完成JSFiddle基准测试(http://jsfiddle.net/WSzec/)显著更快(~20%+会很好)在IE 9+, FF 24+和Chrome 29+。

以下是相关JavaScript代码:当前最快速度:http://jsfiddle.net/WSzec/6/

var 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[""];
}
var 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;
}

编辑1修改了上面的@Bergi的实现,这是目前最快的。顺便说一句,使用“。”用indexOf代替正则表达式。exec”在FF中快了20%左右,但在Chrome中慢了20%;所以我将坚持使用正则表达式,因为它更简单(这里是我尝试使用indexOf来取代正则表达式http://jsfiddle.net/WSzec/2/)。

在@Bergi的想法的基础上,我设法创建了一个更快的非正则表达式版本(在FF快3倍,在Chrome快10%)。http://jsfiddle.net/WSzec/6/在这个(当前)实现中,密钥名称的规则很简单,密钥不能以整数开头或包含句点。

例子:

{"foo":{"bar":[0]}} => {"foo.bar.0":0}

EDIT 3添加@AaditMShah的内联路径解析方法(而不是String.split)有助于提高unflatten性能。我对整体性能的提升非常满意。

最新版本的jsfiddle和jsperf:

http://jsfiddle.net/WSzec/14/

http://jsperf.com/flatten-un-flatten/4


当前回答

下面是我编写的一些代码,用于压平我正在使用的对象。它创建了一个新类,接受每个嵌套字段并将其带入第一层。您可以通过记住键的原始位置将其修改为平直。它还假定键在嵌套对象中也是唯一的。希望能有所帮助。

class JSONFlattener {
    ojson = {}
    flattenedjson = {}

    constructor(original_json) {
        this.ojson = original_json
        this.flattenedjson = {}
        this.flatten()
    }

    flatten() {
        Object.keys(this.ojson).forEach(function(key){
            if (this.ojson[key] == null) {

            } else if (this.ojson[key].constructor == ({}).constructor) {
                this.combine(new JSONFlattener(this.ojson[key]).returnJSON())
            } else {
                this.flattenedjson[key] = this.ojson[key]
            }
        }, this)        
    }

    combine(new_json) {
        //assumes new_json is a flat array
        Object.keys(new_json).forEach(function(key){
            if (!this.flattenedjson.hasOwnProperty(key)) {
                this.flattenedjson[key] = new_json[key]
            } else {
                console.log(key+" is a duplicate key")
            }
        }, this)
    }

    returnJSON() {
        return this.flattenedjson
    }
}

console.log(new JSONFlattener(dad_dictionary).returnJSON())

例如,它可以进行转换

nested_json = {
    "a": {
        "b": {
            "c": {
                "d": {
                    "a": 0
                }
            }
        }
    },
    "z": {
        "b":1
    },
    "d": {
        "c": {
            "c": 2
        }
    }
}

{ a: 0, b: 1, c: 2 }

其他回答

我编写了两个函数来平抑和反平抑一个JSON对象。


扁平化JSON对象:

var flatten = (function (isArray, wrapped) {
    return function (table) {
        return reduce("", {}, table);
    };

    function reduce(path, accumulator, table) {
        if (isArray(table)) {
            var length = table.length;

            if (length) {
                var index = 0;

                while (index < length) {
                    var property = path + "[" + index + "]", item = table[index++];
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            } else accumulator[path] = table;
        } else {
            var empty = true;

            if (path) {
                for (var property in table) {
                    var item = table[property], property = path + "." + property, empty = false;
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            } else {
                for (var property in table) {
                    var item = table[property], empty = false;
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            }

            if (empty) accumulator[path] = table;
        }

        return accumulator;
    }
}(Array.isArray, Object));

性能:

它比Opera中当前的解决方案要快。目前的解决方案在Opera中要慢26%。 它比Firefox当前的解决方案要快。当前的解决方案在Firefox中要慢9%。 它比当前Chrome的解决方案要快。目前Chrome的解决方案要慢29%。


Unflatten一个JSON对象:

function unflatten(table) {
    var result = {};

    for (var path in table) {
        var cursor = result, length = path.length, property = "", index = 0;

        while (index < length) {
            var char = path.charAt(index);

            if (char === "[") {
                var start = index + 1,
                    end = path.indexOf("]", start),
                    cursor = cursor[property] = cursor[property] || [],
                    property = path.slice(start, end),
                    index = end + 1;
            } else {
                var cursor = cursor[property] = cursor[property] || {},
                    start = char === "." ? index + 1 : index,
                    bracket = path.indexOf("[", start),
                    dot = path.indexOf(".", start);

                if (bracket < 0 && dot < 0) var end = index = length;
                else if (bracket < 0) var end = index = dot;
                else if (dot < 0) var end = index = bracket;
                else var end = index = bracket < dot ? bracket : dot;

                var property = path.slice(start, end);
            }
        }

        cursor[property] = table[path];
    }

    return result[""];
}

性能:

它比Opera中当前的解决方案要快。当前的解决方案在Opera中要慢5%。 它比Firefox当前的解决方案要慢。我的解决方案在Firefox中慢了26%。 它比当前Chrome的解决方案要慢。我的解决方案在Chrome浏览器中要慢6%。


将JSON对象平放和反平放:

总的来说,我的解决方案的性能与当前解决方案一样好,甚至更好。

性能:

它比Opera中当前的解决方案要快。当前的解决方案在Opera中要慢21%。 它和Firefox当前的解决方案一样快。 它比Firefox当前的解决方案要快。目前Chrome的解决方案要慢20%。


输出格式:

扁平对象使用点符号表示对象属性,用方括号表示数组下标:

{foo:{bar:false}} => {"foo.bar":false} {: [{b:[“c”、“d "]}]} => {" [0]。b[0]”:“c”、“[0]。b[1]”:“d”} [1, 2、(3、4)、5)、6)= >{“[0]”:1、“[1][0]”:2,”[1][1][0]”:3”[1][1][1]”:4,”[1][2]”:5,“[2]”:6}

在我看来,这种格式比只使用点表示法更好:

{foo:{bar:false}} => {"foo.bar":false} {: [{b:[“c”、“d "]}]} => {" a.0.b.0”:“c”、“a.0.b.1”:“d”} [1, 2、(3、4)、5)、6)= >{“0”:1、“1.0”:2,“1.1.0”:3、“1.1.1”:4,“1.2”:5,“2”:6}


优点:

压扁一个物体比目前的解决方案更快。 使物体变平或变平的速度与当前解决方案一样快,甚至更快。 为了可读性,扁平对象同时使用点符号和方括号符号。

缺点:

在大多数(但不是所有)情况下,将对象平展比当前解决方案要慢。


当前的JSFiddle演示给出以下值作为输出:

Nested : 132175 : 63
Flattened : 132175 : 564
Nested : 132175 : 54
Flattened : 132175 : 508

我更新的JSFiddle演示给出以下值作为输出:

Nested : 132175 : 59
Flattened : 132175 : 514
Nested : 132175 : 60
Flattened : 132175 : 451

我不太确定这意味着什么,所以我将继续使用jsPerf结果。毕竟jsPerf是一个性能基准测试工具。JSFiddle不是。

试试这个:

    function getFlattenObject(data, response = {}) {
  for (const key in data) {
    if (typeof data[key] === 'object' && !Array.isArray(data[key])) {
      getFlattenObject(data[key], response);
    } else {
      response[key] = data[key];
    }
  }
  return response;
}

下面是我在PowerShell中整理的flatten的递归解决方案:

#---helper function for ConvertTo-JhcUtilJsonTable
#
function getNodes {
    param (
        [Parameter(Mandatory)]
        [System.Object]
        $job,
        [Parameter(Mandatory)]
        [System.String]
        $path
    )

    $t = $job.GetType()
    $ct = 0
    $h = @{}

    if ($t.Name -eq 'PSCustomObject') {
        foreach ($m in Get-Member -InputObject $job -MemberType NoteProperty) {
            getNodes -job $job.($m.Name) -path ($path + '.' + $m.Name)
        }
        
    }
    elseif ($t.Name -eq 'Object[]') {
        foreach ($o in $job) {
            getNodes -job $o -path ($path + "[$ct]")
            $ct++
        }
    }
    else {
        $h[$path] = $job
        $h
    }
}


#---flattens a JSON document object into a key value table where keys are proper JSON paths corresponding to their value
#
function ConvertTo-JhcUtilJsonTable {
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [System.Object[]]
        $jsonObj
    )

    begin {
        $rootNode = 'root'    
    }
    
    process {
        foreach ($o in $jsonObj) {
            $table = getNodes -job $o -path $rootNode

            # $h = @{}
            $a = @()
            $pat = '^' + $rootNode
            
            foreach ($i in $table) {
                foreach ($k in $i.keys) {
                    # $h[$k -replace $pat, ''] = $i[$k]
                    $a += New-Object -TypeName psobject -Property @{'Key' = $($k -replace $pat, ''); 'Value' = $i[$k]}
                    # $h[$k -replace $pat, ''] = $i[$k]
                }
            }
            # $h
            $a
        }
    }

    end{}
}

例子:

'{"name": "John","Address": {"house": "1234", "Street": "Boogie Ave"}, "pets": [{"Type": "Dog", "Age": 4, "Toys": ["rubberBall", "rope"]},{"Type": "Cat", "Age": 7, "Toys": ["catNip"]}]}' | ConvertFrom-Json | ConvertTo-JhcUtilJsonTable
Key              Value
---              -----
.Address.house   1234
.Address.Street  Boogie Ave
.name            John
.pets[0].Age     4
.pets[0].Toys[0] rubberBall
.pets[0].Toys[1] rope
.pets[0].Type    Dog
.pets[1].Age     7
.pets[1].Toys[0] catNip
.pets[1].Type    Cat

这里有另一个方法,比上面的答案运行得慢(大约1000毫秒),但有一个有趣的想法:-)

它不是遍历每个属性链,而是只选择最后一个属性,并使用一个查找表来存储其余属性,从而存储中间结果。这个查找表将被迭代,直到没有剩余的属性链,并且所有值都驻留在未协同的属性上。

JSON.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
        props = Object.keys(data),
        result, p;
    while(p = props.shift()) {
        var m = regex.exec(p),
            target;
        if (m.index) {
            var rest = p.slice(0, m.index);
            if (!(rest in data)) {
                data[rest] = m[2] ? [] : {};
                props.push(rest);
            }
            target = data[rest];
        } else {
            target = result || (result = (m[2] ? [] : {}));
        }
        target[m[2] || m[1]] = data[p];
    }
    return result;
};

它目前使用表的数据输入参数,并在上面放置了许多属性-一个非破坏性的版本也应该是可能的。也许巧妙地使用lastIndexOf会比正则表达式执行得更好(取决于正则表达式引擎)。

在这里看到它的行动。

三年半后……

对于我自己的项目,我想在mongoDB点表示法中平坦JSON对象,并提出了一个简单的解决方案:

/**
 * 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
}

特性和/或注意事项

它只接受JSON对象。因此,如果你传递类似{a:() =>{}}的东西,你可能得不到你想要的! 它删除空数组和对象。所以这个{a: {}, b:[]}被平化为{}。