如何使用javascript合并数组和json对象

时间:2015-05-05 08:34:35

标签: json

如何合并这两个JSON变量?

var j1 = {"a":{"hello":"test"},"b":['array']};
var j2 = {"b":{"hi":"world"}};

$.extend(true,{},j1,j2) does not work it removes my ['array'] value

我想要一个像这样的结果

  

" b":{" hi":" world"},[' array']

谢谢!

1 个答案:

答案 0 :(得分:0)

此代码可以帮助您

function merge (obj1, obj2) {
   var obj = JSON.parse(JSON.stringify(obj1)); // Clone object
   for(var key in obj) {
      if(obj2.hasOwnProperty(key)) {
         obj[key] = [obj[key], obj2[key]];
      }
   }

   return obj;
}

示例:

var j1 = {"a":{"hello":"test"},"b":['array']};
var j2 = {"b":{"hi":"world"}};
obj = merge(j1, j2);


/* Result :

{
   "a": {
      "hello": "test"
   },
   "b": [
      [
         "array"
      ],
      {
         "hi": "world"
      }
   ]
}

*/