Mur*_*ain 66 javascript jquery json
我有两个json数组
var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]
Run Code Online (Sandbox Code Playgroud)
我希望他们合并到单个数组
var finalObj = [{id:1, name: 'xxx' ...},{id:2, name: 'xyz' ...}]
Run Code Online (Sandbox Code Playgroud)
问候
Que*_*tin 115
你想要这个concat
方法.
var finalObj = json1.concat(json2);
Run Code Online (Sandbox Code Playgroud)
SpY*_*3HH 37
首次出现时,单词"merg"会让人觉得你需要使用.extend,这是正确的jQuery方式来"合并"JSON对象.但是,$.extend(true, {}, json1, json2);
将导致共享相同键名的所有值都被params中提供的最新值覆盖.正如对您的问题的审核所示,这是不受欢迎的.
你寻求的是一个简单的javascript函数,称为.concat.哪个会像:
var finalObj = json1.concat(json2);
Run Code Online (Sandbox Code Playgroud)
虽然这不是本机jQuery函数,但您可以轻松地将其添加到jQuery库中以供将来使用,如下所示:
;(function($) {
if (!$.concat) {
$.extend({
concat: function() {
return Array.prototype.concat.apply([], arguments);
}
});
}
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
然后按需要回忆起它:
var finalObj = $.concat(json1, json2);
Run Code Online (Sandbox Code Playgroud)
您还可以将它用于此类型的多个数组对象,例如:
var finalObj = $.concat(json1, json2, json3, json4, json5, ....);
Run Code Online (Sandbox Code Playgroud)
如果你真的想要它jQuery风格,非常简短和甜蜜(又缩小)
;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
Run Code Online (Sandbox Code Playgroud)
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
$(function() {
var json1 = [{id:1, name: 'xxx'}],
json2 = [{id:2, name: 'xyz'}],
json3 = [{id:3, name: 'xyy'}],
json4 = [{id:4, name: 'xzy'}],
json5 = [{id:5, name: 'zxy'}];
console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));
console.log($.concat(json1, json2, json3));
console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));
console.log($.concat(json1, json2, json3, json4, json5));
console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));
console.log($.concat(json4, json1, json2, json5));
});
Run Code Online (Sandbox Code Playgroud)
center { padding: 3em; }
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<center>See Console Log</center>
Run Code Online (Sandbox Code Playgroud)
您可以使用 Es 6 新功能来做到这一点:
var json1 = [{id:1, name: 'xxx' , ocupation : 'Doctor' }];
var json2 = [{id:2, name: 'xyz' ,ocupation : 'SE'}];
var combineJsonArray = [...json1 , ...json2];
//output should like this [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
{ id: 2, name: 'xyz', ocupation: 'SE' } ]
Run Code Online (Sandbox Code Playgroud)
或者您可以在两个 json 数组之间放置额外的字符串或任何内容:
var json3 = [...json1 ,"test", ...json2];
// output should like this : [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
'test',
{ id: 2, name: 'xyz', ocupation: 'SE' } ]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
170350 次 |
最近记录: |