如果需要将下面的json对象合并:
- var a ={"a":"1","b":"2"}
- var b ={"c":"3","d":"4","e":"5"}
想得到结果:
- var c ={"a":"1","b":"2","c":"3","d":"4","e":"5"}
直接使用js的话,可以用一下方法:
- <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()方法,该方法有两种模式;
jQuery.extend( target [, object1 ] [, objectN ] ) #将后面的对象合并到新的对象中{}
jQuery.extend( [deep ], target, object1 [, objectN ] ) #将后面的对象合并到新的对象中{},如果深度deep为true则将递归合并成为新对象.
实例:
- <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"}}