compressing object hierarchies in JavaScript

前端 未结 3 1571
抹茶落季
抹茶落季 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:32

    Here's a quick one, but watch out, b/c it will not work w/ arrays and null values (b/c their typeof returns "object").

    var flatten = function(obj, prefix) {
      if(typeof prefix === "undefined") {
        prefix = "";
      }
      var copy = {};
      for (var p in obj) {
        if(obj.hasOwnProperty(p)) {
          if(typeof obj[p] === "object") {
            var tmp = flatten(obj[p], p + "_");
            for(var q in tmp) {
              if(tmp.hasOwnProperty(q)) {
                copy[prefix + q] = tmp[q];
              }
            }
          }
          else {
            copy[prefix + p] = obj[p];
          }
        }
      }
      return copy;
    }
    
    var myObj = {
      a: "level 1",
      b: {
        a: "level 2",
        b: {
          a: "level 3",
          b: "level 3"
        }
      }
    }
    
    var flattened = flatten(myObj);
    

提交回复
热议问题