|
|
道上混的创口贴 · Array.prototype.some() ...· 1 月前 · |
|
|
没人理的油条 · jq命令 :: AWS Workshop· 1 周前 · |
|
|
骑白马的香菜 · 在线 JSON 数组 转 Pandas ...· 1 周前 · |
|
|
阳光的牙膏 · Class (Java 2 ...· 4 天前 · |
|
|
瘦瘦的棒棒糖 · OpenCV 4基础篇| ...· 2 天前 · |
|
|
跑龙套的单杠 · 分享6个对象数组去重的方法-腾讯云开发者社区 ...· 2 月前 · |
|
|
强悍的双杠 · Datagrip连接SQLServer失败 ...· 1 年前 · |
|
|
酷酷的火龙果 · 导入numpy后未定义np。-腾讯云开发者社 ...· 2 年前 · |
|
|
热情的烤面包 · 记一次Spring ...· 2 年前 · |
|
|
想旅行的钥匙 · Laravel查询一时间段内的数据库数据_猿 ...· 2 年前 · |
我有两个json数组,比如
var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]
我希望它们合并到单个数组中
var finalObj = [{id:1, name: 'xxx' ...},{id:2, name: 'xyz' ...}]
第一次出现时,单词"merg“会让人认为您需要使用
.extend
,这是”合并“JSON对象的正确jQuery方式。但是,
$.extend(true, {}, json1, json2);
将导致所有共享相同键名的值被参数中提供的最新值覆盖。正如对您的问题的回顾所示,这是不受欢迎的。
您要寻找的是一个简单的javascript函数,称为 .concat 。它的工作原理如下:
var finalObj = json1.concat(json2);
虽然这不是本机jQuery函数,但您可以轻松地将其添加到jQuery库中,以便将来简单使用,如下所示:
;(function($) {
if (!$.concat) {
$.extend({
concat: function() {
return Array.prototype.concat.apply([], arguments);
})(jQuery);
然后根据需要调用它,如下所示:
var finalObj = $.concat(json1, json2);
还可以将其用于此类型的多个数组对象,如下所示:
var finalObj = $.concat(json1, json2, json3, json4, json5, ....);
如果你真的想要它的jQuery风格和非常简短和甜蜜(也就是缩小)
;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
;(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));
});
center { padding: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<center>See Console Log</center>
您需要
concat
方法。
var finalObj = json1.concat(json2);
您可以尝试合并
var finalObj = $.merge(json1, json2);
也许,您可以使用javascript的数组语法:
var finalObj =[json1 , json2]