![]() |
慷慨大方的麦片 · JavaScript---Dom树详解,节点 ...· 2 月前 · |
![]() |
坏坏的西瓜 · Flutter中Map、List数组的常用方 ...· 2 月前 · |
![]() |
酷酷的鸵鸟 · React中如何动态添加和删除元素_reac ...· 1 月前 · |
![]() |
知识渊博的柚子 · 在Swift中展平数组的数组开发者社区· 1 月前 · |
![]() |
腼腆的饼干 · array(C++/CLI 和 ...· 1 月前 · |
![]() |
爽快的盒饭 · org.springframework.me ...· 8 月前 · |
![]() |
很酷的大蒜 · 如何通过Python ...· 9 月前 · |
![]() |
低调的镜子 · vue中数组的相关方法_vue ...· 1 年前 · |
![]() |
可爱的南瓜 · java - Thymeleaf with ...· 2 年前 · |
![]() |
腹黑的刺猬 · SpringCloud-技术专区-Gatew ...· 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]
![]() |
慷慨大方的麦片 · JavaScript---Dom树详解,节点查找方式(直接(id,class,tag),间接(父子,兄弟)),节点操作(增删改查,赋值节点,替换节点,),节点属性操作(增删改查),节点文本的操作(增删 2 月前 |
![]() |
知识渊博的柚子 · 在Swift中展平数组的数组开发者社区 1 月前 |
![]() |
爽快的盒饭 · org.springframework.messaging.MessagingException: send message Exception; nested exception is org.ap 8 月前 |
![]() |
低调的镜子 · vue中数组的相关方法_vue 定义数组-CSDN博客 1 年前 |