|
|
大方的香烟 · JavaScript Array ...· 2 月前 · |
|
|
跑龙套的单杠 · 分享6个对象数组去重的方法开发者社区· 2 月前 · |
|
|
刚失恋的黄瓜 · 为什么C数组下标从0开始,而不是从1开始_c ...· 2 月前 · |
|
|
冷冷的草稿本 · txt文件转数组_python读取txt为数组· 2 月前 · |
|
|
道上混的创口贴 · Array.prototype.some() ...· 4 周前 · |
|
|
聪明的课本 · 非洲国家加快推进基础设施建设(国际视点)-- ...· 3 月前 · |
|
|
淡定的核桃 · 人民日报海外版-人民网· 4 月前 · |
|
|
求醉的大熊猫 · 中国的兵役制度(二):义务兵役制_中国人大网· 1 年前 · |
|
|
活泼的楼梯 · 如果黄家驹现在还活着,beyond的发展和现 ...· 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]
|
|
跑龙套的单杠 · 分享6个对象数组去重的方法开发者社区 2 月前 |
|
|
冷冷的草稿本 · txt文件转数组_python读取txt为数组 2 月前 |
|
|
淡定的核桃 · 人民日报海外版-人民网 4 月前 |
|
|
求醉的大熊猫 · 中国的兵役制度(二):义务兵役制_中国人大网 1 年前 |