jquery merge two objects

后端 未结 5 2172
迷失自我
迷失自我 2021-02-07 04:52

How can I merge jquery objects together

I have

 {
  \"merchantcontract\":\"Ready Reserve Foods 10104.01\",
  \"merchantcontractid\":\"c4253769-5a57-e11         


        
相关标签:
5条回答
  • 2021-02-07 05:25

    If you want to update your existing object, use:

    $.extend(obj1, obj2); //update obj1 and put all obj2 values in it.
    

    $.extend will change the values of your existing object

    To create a new third object that is the sum of both objects, you can use this function

    function merger_objects(obj1,obj2){
      $.each(obj2, function(key, value) {
         obj1[key] = value;    
      });
     return obj1;
    }
    

    Example

    var fruit = {apple:"sweet",graps:"bitter"}
    var vege = {cucamber:"bitter",letuce:"bitter"}
    
    var fruit_and_vege = merger_objects(fruit,vege); 
    //returns {apple:"sweet",graps:"bitter",cucamber:"bitter",letuce:"bitter"}
    
    0 讨论(0)
  • 2021-02-07 05:41

    can you put them in an array?

    var myObjects = [];
    

    and in your each where they are created just add:

    myObjects.push(newObject);
    
    0 讨论(0)
  • 2021-02-07 05:44

    jQuery's $.extend will do what you want.

    //merging two objects into new object
    var new_object = $.extend({}, object1, object2);
    
    //merge object2 into object1
    $.extend(object1, object2);
    
    0 讨论(0)
  • In case you wish to merge them recursively, $.extend offers the argument deep. In case deep=true the merge become recursively. An example above,

    // Initialize two objects.
    var json1 = { "a": { "a1": "value1", "a2": "value2" }};
    var json2 = { "a": { "a3": "value3" }};
    
    // Merge them recursively.
    var newJson = $.extend(true, {}, json1, json2);
    
    // Test it.
    if (newJson.a.a1 && newJson.a.a3) {
        console.log("Success");
    }
    
    0 讨论(0)
  • 2021-02-07 05:51
    anObj={'propone':'1', 'proptwo':'2'};
    anotherObj={'propel':'11', 'proptlv':'12'};
    var opts = {};
    $.extend(opts, anObj, anotherObj, { 
        bar: "baz",
        thing: "foo"
    });
    console.log(opts);
    

    Example

    0 讨论(0)
提交回复
热议问题