compressing object hierarchies in JavaScript

前端 未结 3 1598
抹茶落季
抹茶落季 2021-02-06 01:14

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

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

compress(         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 01:33

    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]"
      

提交回复
热议问题