各位js大神,请教以下如下俩个对象数组如何合并为一个?
[{"msg":"你也好","from":"libai"},{"msg":"我是李白,你是谁","from":"libai"}]
arr2:
[{"msg":"你好","from":"admin"},{"msg":"LOL吗","from":"admin"},{"msg":"我是系统管理员,你是李白吗","from":"admin"}]
我想让合并后的数组为
[{"msg":"你也好","from":"libai"},{"msg":"我是李白,你是谁","from":"libai"},{"msg":"你好","from":"admin"},{"msg":"LOL吗","from":"admin"},{"msg":"我是系统管理员,你是李白吗","from":"admin"}]
,应该调用什么方法呢 展开
js的数组合并有三种方法,任何一种都可以做到你需要的结果,如下:
concat 方法
var arr1=[{"msg":"你也好","from":"libai"},{"msg":"我是李白,你是谁","from":"libai"}];
var arr2=[{"msg":"你好","from":"admin"},{"msg":"LOL吗","from":"admin"},{"msg":"我是系统管理员,你是李白吗","from":"admin"}];
var arr=arr1.concat(arr2);console.log(c);//你要的结果,不改变arr1和arr2
循环遍历
var arr1=[{"msg":"你也好","from":"libai"},{"msg":"我是李白,你是谁","from":"libai"}];
var arr2=[{"msg":"你好","from":"admin"},{"msg":"LOL吗","from":"admin"},{"msg":"我是系统管理员,你是李白吗","from":"admin"}];
for(var i=0;i<arr2.length;i++){
arr1.push(arr2[i]);
}
console.log(arr1);//你要的结果,但是这个是直接改变了arr1这个数组
apply方法
合并数组arr1和数组arr2,使用Array.prototype.push.apply(arr1,arr2) or arr1.push.apply(arr1,arr2);
var arr1=[{"msg":"你也好","from":"libai"},{"msg":"我是李白,你是谁","from":"libai"}];
var arr2=[{"msg":"你好","from":"admin"},{"msg":"LOL吗","from":"admin"},{"msg":"我是系统管理员,你是李白吗","from":"admin"}];
Array.prototype.push.apply(arr1,arr2); //或者 arr1.push.apply(arr1,arr2);
console.log(arr1) //改变了arr1