我将一些代码放在一起,以平抑和反平抑复杂/嵌套的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


当前回答

Object.prototype.flatten = function (obj) { let ans = {}; let anotherObj = { ...obj }; function performFlatten(anotherObj) { Object.keys(anotherObj).forEach((key, idx) => { if (typeof anotherObj[key] !== 'object') { ans[key] = anotherObj[key]; console.log('ans so far : ', ans); } else { console.log(key, { ...anotherObj[key] }); performFlatten(anotherObj[key]); } }) } performFlatten(anotherObj); return ans; } let ans = flatten(obj); console.log(ans);

其他回答

Object.prototype.flatten = function (obj) { let ans = {}; let anotherObj = { ...obj }; function performFlatten(anotherObj) { Object.keys(anotherObj).forEach((key, idx) => { if (typeof anotherObj[key] !== 'object') { ans[key] = anotherObj[key]; console.log('ans so far : ', ans); } else { console.log(key, { ...anotherObj[key] }); performFlatten(anotherObj[key]); } }) } performFlatten(anotherObj); return ans; } let ans = flatten(obj); console.log(ans);

三年半后……

对于我自己的项目,我想在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:[]}被平化为{}。

我想添加一个新版本的flatten case(这是我需要的:)),根据我与上面的jsFiddler的探测,比当前选择的略快。 此外,我个人认为这段代码更有可读性,这对多人开发项目当然很重要。

function flattenObject(graph) {
    let result = {},
        item,
        key;

    function recurr(graph, path) {
        if (Array.isArray(graph)) {
            graph.forEach(function (itm, idx) {
                key = path + '[' + idx + ']';
                if (itm && typeof itm === 'object') {
                    recurr(itm, key);
                } else {
                    result[key] = itm;
                }
            });
        } else {
            Reflect.ownKeys(graph).forEach(function (p) {
                key = path + '.' + p;
                item = graph[p];
                if (item && typeof item === 'object') {
                    recurr(item, key);
                } else {
                    result[key] = item;
                }
            });
        }
    }
    recurr(graph, '');

    return result;
}

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

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 }

试试这个:

    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;
}