jquery merge two objects

后端 未结 5 2255
迷失自我
迷失自我 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"}
    

提交回复
热议问题