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

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

问题描述

是否有一个通用的方法来压缩嵌套对象到单个级别:

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

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



会涉及到一些递归,但我想我不需要在这里重新创建轮子...!

解决方案

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

返回;
}

您可以通过传递 true 到第二个参数。



几个警告:




  • 递归对象将无法工作。例如:

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


  • li>

    像ruquay的答案,这拉出数组元素就像正常的对象属性。如果你想保持数组完整,添加 || prop instanceof Array


  • 如果从不同的窗口或框架对对象调用此方法,则不会包含日期和正则表达式,因为 instanceof 无法正常工作。你可以通过使用默认的toString方法替换它来解决这个问题:

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



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

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

A few caveats:

  • recursive objects will not work. For example:

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

    will recurse until it throws an exception.

  • 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.

  • 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天全站免登陆