在 JavaScript 中压缩对象层次结构 [英] compressing object hierarchies in JavaScript

查看:22
本文介绍了在 JavaScript 中压缩对象层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种通用方法可以将嵌套对象压缩"到单个级别:

Is there a generic approach to "compressing" nested objects to a single level:

var myObj = {
    a: "hello",
    b: {
        c: "world"
    }
}

compress(myObj) == {
    a: "hello",
    b_c: "world"
}

我想这会涉及到一些递归,但我认为我不需要在这里重新发明轮子......!?

I guess there would be some recursion involved, but I figured I don't need to reinvent the wheel here... !?

推荐答案

function flatten(obj, includePrototype, into, prefix) {
    into = into || {};
    prefix = prefix || "";

    for (var k in obj) {
        if (includePrototype || obj.hasOwnProperty(k)) {
            var prop = obj[k];
            if (prop && typeof prop === "object" &&
                !(prop instanceof Date || prop instanceof RegExp)) {
                flatten(prop, includePrototype, into, prefix + k + "_");
            }
            else {
                into[prefix + k] = prop;
            }
        }
    }

    return into;
}

您可以通过将 true 传递给第二个参数来包含继承成员.

You can include members inherited members by passing true into the second parameter.

一些注意事项:

  • 递归对象不起作用.例如:

  • recursive objects will not work. For example:

var o = { a: "foo" };
o.b = o;
flatten(o);

会递归直到抛出异常.

就像 ruquay 的回答一样,这会像普通对象属性一样提取数组元素.如果要保持数组完整,请将|| prop instanceof Array"添加到异常中.

Like ruquay's answer, this pulls out array elements just like normal object properties. If you want to keep arrays intact, add "|| prop instanceof Array" to the exceptions.

如果您从不同的窗口或框架对对象调用此方法,日期和正则表达式将不包括在内,因为 instanceof 将无法正常工作.您可以通过将其替换为默认的 toString 方法来解决此问题,如下所示:

If you call this on objects from a different window or frame, dates and regular expressions will not be included, since instanceof will not work properly. You can fix that by replacing it with the default toString method like this:

Object.prototype.toString.call(prop) === "[object Date]"
Object.prototype.toString.call(prop) === "[object RegExp]"
Object.prototype.toString.call(prop) === "[object Array]"

这篇关于在 JavaScript 中压缩对象层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆