连接两个json对象

时间:2014-04-07 08:44:07

标签: javascript jquery json

有没有办法聚合两个json对象并将结果分配给第一个对象 我有两个Json对象,我想将它们聚合成一个对象

               <script type="text/javascript">
               $(document).ready(function () {

                    var FirstObject= [
                    { "label": "salem", "actor": "" },
                { "label": "Aragorn", "actor": "Viggo Mortensen" },
                { "label": "Arwen", "actor": "Liv Tyler" },
                { "label": "Bilbo Baggins", "actor": "Ian Holm" },
                { "label": "Boromir", "actor": "Sean Bean" },
                { "label": "Frodo Baggins", "actor": "Elijah Wood" },
            { "label": "Gandalf", "actor": "Ian McKellen" },
                { "label": "Gimli", "actor": "John Rhys-Davies" },
                { "label": "Gollum", "actor": "Andy Serkis" },
            { "label": "Legolas", "actor": "Orlando Bloom" },
                { "label": "Meriadoc Merry Brandybuck", "actor": "Dominic Monaghan" },
                { "label": "Peregrin Pippin Took", "actor": "Billy Boyd" },
         { "label": "Samwise Gamgee", "actor": "Sean Astin" }
                ];
        $("#search").keyup(function () {


            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                url: "WebService1.asmx/GetDocumentNames",
                data: '{ }',
                success: function (data) { 
                     **FirstObject =data.d**




                },
                error: function () { aler("Salem Error"); }
            }

   );
        });



    });


</script>

所以语句 FirstObject = data.d 我想要聚合

5 个答案:

答案 0 :(得分:3)

像这样使用jQuery extend

// first argument tells jQuery's extend to deep copy the properties
$.extend( true, FirstObject, data.d );

引用jQuery文档:

  

递归合并两个对象,修改第一个。

答案 1 :(得分:0)

看看下面的例子:

var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);

答案 2 :(得分:0)

您的变量FirstObject实际上是一个数组,假设您收到的不是数组而是JSON对象要追加或聚合到数组,您只需要调用数组的方法push

FirstObject.push(data.d);

如果您收到的是JSON数组而不是JSON对象,则可以在数组中使用concat方法。

FirstObject.concat(data.d);

答案 3 :(得分:0)

如果要合并JSON对象并维护公共密钥。

&#13;
&#13;
var object1 = {
  'key1': 10,
  'key2': 'Hello ',
  'key3': [
    'I',
    'am'
  ],
  'key4': {
    'key5': 'Hi',
    'key6': 11
  }
};
var object2 = {
  'key1': 11,
  'key2': 'World',
  'key3': [
    'an',
    'Array'
  ],
  'key4': {
    'key5': ' there',
    'key6': '#SomeRandomString'
  }
};

function isArray(value) {
  return Object.prototype.toString.call(value) === '[object Array]';
}

function isObject(value) {
  return Object.prototype.toString.call(value) === '[object Object]';
}

var result = {};
for (var key in object1) {
  if (object1.hasOwnProperty(key) && object2.hasOwnProperty(key)) {
  
  //check if the value is of type array (works for key 3)
    if (isArray(object1[key]) && isArray(object2[key])) {
      result[key] = [];
      for (var i in object1[key]) {
        result[key].push(object1[key][i])
      }
      for (var i in object2[key]) {
        result[key].push(object2[key][i])
      }
    } 
    
  //check if the value is of type object (works for key 4)
    else if (isObject(object1[key])) {
      result[key] = {};
      for (var key_inner in object1[key]) {
        if (object1[key].hasOwnProperty(key_inner) && object2[key].hasOwnProperty(key_inner)) {
          result[key][key_inner] = object1[key][key_inner] + object2[key][key_inner];
        }
      }
    } else {
      result[key] = object1[key] + object2[key];
    }
  }
}
//console.log(JSON.stringify(result));
console.log(result);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您可以使用 Object.assign()方法来串联json对象。 Object.assign()方法用于将所有可枚举的自身属性的值从一个或多个源对象复制到目标对象。[1]

var o1 = { a: 1 }, o2 = { b: 2 }, o3 = { c: 3 };        
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }