admin管理员组

文章数量:1292344

is there any way to Aggregation two json object together and assign the result to the first object i have tow Json object and i want to Aggregation them into one object

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

so on the statement FirstObject =data.d i want the Aggregation

is there any way to Aggregation two json object together and assign the result to the first object i have tow Json object and i want to Aggregation them into one object

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

so on the statement FirstObject =data.d i want the Aggregation

Share Improve this question edited Apr 7, 2014 at 8:46 salem salah asked Apr 7, 2014 at 8:44 salem salahsalem salah 231 gold badge1 silver badge5 bronze badges 3
  • Have a look at jQuery’s extend that merges deep objects effectively: api.jquery./jquery.extend – David Hellsing Commented Apr 7, 2014 at 8:47
  • "Concatenating" two objects is a confusing choice of words and I also understood he wanted to "merge" two objects, but I think he actually wants to concatenate two arrays, or add an object to an array... – Djizeus Commented Apr 7, 2014 at 8:52
  • possible duplicate of Concat JSON objects – radia Commented Apr 7, 2014 at 8:52
Add a ment  | 

5 Answers 5

Reset to default 3

Use jQuery extend like this:

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

quote from jQuery documentation:

Merge two objects recursively, modifying the first.

Your variable FirstObject is actually an array, and assuming what you receive is not an Array but a JSON Object to append or aggregate it to the array, you just need to call the Array's method push.

FirstObject.push(data.d);

If what you're receiving is a JSON Array rather that a JSON Object, you could use the concat method in the array.

FirstObject.concat(data.d);

Take a look in below example:

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

If you want to merge the JSON objects and maintain the mon keys.

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);

You can use Object.assign() method to concatenate a json object. The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.[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 }

本文标签: javascriptConcatenate two json objectStack Overflow