若是須要將下面的json對象合併:javascript
- var a ={"a":"1","b":"2"}
- var b ={"c":"3","d":"4","e":"5"}
想獲得結果:java
- var c ={"a":"1","b":"2","c":"3","d":"4","e":"5"}
直接使用js的話,能夠用一下方法:jquery
- <script>
- function extend(des, src, override){
- if(src instanceof Array){
- for(var i = 0, len = src.length; i < len; i++)
- extend(des, src[i], override);
- }
- for( var i in src){
- if(override || !(i in des)){
- des[i] = src[i];
- }
- }
- return des;
- }
- var a ={"a":"1","b":"2"}
- var b ={"c":"3","d":"4","e":"5"}
- var c = extend({}, [a,b]);
- alert(c.a);
- </script>
固然若是你加載了jquery,那就更方便了。可使用$.extend()方法,該方法有兩種模式;json
實例:
- <script type="text/javascript">
- # 請記得先加載jquery
- var a ={"a":"1","b":"2"}
- var b ={"c":"3","d":"4","e":"5"}
- var c = $.extend({}, a,b);
- console.log(c);
- </script>
若是是:
var c = $.extend({}, [a,b]);
-->{"0":{"a":"1","b":"2"},"1":{"c":"3","d":"4","e":"5"}}