在javascript中合并对象文字/ json

时间:2013-11-13 05:28:30

标签: javascript jquery json

我正在尝试将所有数据对象连接到一个全部链接的数据对象

var person1 = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
        }
    }
};


var person2 = {
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};

我希望它看起来像这样:

var mergedObjects = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
        }
    },
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};

我知道如何使用Arrays执行此操作,但我如何在javascript中执行此操作作为维护正确结构的JSON对象

3 个答案:

答案 0 :(得分:1)

检查出来......

这里有答案...... How can I merge properties of two JavaScript objects dynamically?

JS Fiddle

<强> JS:

 function mergeRecursive(obj1, obj2) {

  for (var p in obj2) {
    try {
      // Property in destination object set; update its value.
      if ( obj2[p].constructor==Object ) {
        obj1[p] = mergeRecursive(obj1[p], obj2[p]);

      } else {
        obj1[p] = obj2[p];

      }

    } catch(e) {
      // Property in destination object not set; create it and set its value.
      obj1[p] = obj2[p];

    }
  }

  return obj1;
}

var person1 = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
        }
    }
};


var person2 = {
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};

console.log(mergeRecursive(person1, person2));

答案 1 :(得分:0)

查看此帖子:link

var person1 = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
        }
    }
};


var person2 = {
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};


function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}



merge_options(person1,person2);

答案 2 :(得分:0)

您可以使用jQuery轻松完成此操作:

var person1 = {
    hello: {
        "david": {
            "hours": "44",
            "money": "22"
         }
    }
};


var person2 = {
    world: {
        "pearce": {
            "hours": "21",
            "money": "11"
        }
    }
};

var mergedObjects = $.extend({}, person1, person2);

console.dir(mergedObjects);