JS與JQ合併對象

若是須要將下面的json對象合併:javascript

  1. var a ={"a":"1","b":"2"}
  2. var b ={"c":"3","d":"4","e":"5"}

想獲得結果:java

  1. var c ={"a":"1","b":"2","c":"3","d":"4","e":"5"}

直接使用js的話,能夠用一下方法:jquery

  1. <script>
  2. function extend(des, src, override){
  3.    if(src instanceof Array){
  4.        for(var i = 0, len = src.length; i < len; i++)
  5.             extend(des, src[i], override);
  6.    }
  7.    for( var i in src){
  8.        if(override || !(i in des)){
  9.            des[i] = src[i];
  10.        }
  11.    }
  12.    return des;
  13. }
  14. var a ={"a":"1","b":"2"}
  15. var b ={"c":"3","d":"4","e":"5"}
  16. var c = extend({}, [a,b]);
  17. alert(c.a);
  18. </script>

固然若是你加載了jquery,那就更方便了。可使用$.extend()方法,該方法有兩種模式;json

jQuery.extend( target [, object1 ] [, objectN ] )  #將後面的對象合併到新的對象中{}

jQuery.extend( [deep ], target, object1 [, objectN ] )  #將後面的對象合併到新的對象中{},若是深度deep爲true則將遞歸合併成爲新對象.

實例:

    1. <script type="text/javascript">
    2.     # 請記得先加載jquery
    3.     var a ={"a":"1","b":"2"}
    4.     var b ={"c":"3","d":"4","e":"5"}
    5.     var c = $.extend({}, a,b);
    6.     console.log(c);
    7. </script>
      若是是:
      var c = $.extend({}, [a,b]);
      -->{"0":{"a":"1","b":"2"},"1":{"c":"3","d":"4","e":"5"}}
相關文章
相關標籤/搜索