简体   繁体   English

如何将对象从oner数组推到另一个数组?

[英]How to push object from oner array to another?

I have two arrays now once i rendered the data from backend i want to push just object from array2 to array1 not the array itself. 我现在有两个数组,一旦我从后端渲染了数据,我想将对象仅从array2推送到array1而不是数组本身。

How can i just push object from array2 to array1 I dont want to push as array. 我如何才能将对象从array2推送到array1我不想将其推送为数组。

ctrl.js

var array1 = [{name:'john', address:'cliffwood ave'}]

var array2 = [{name:'Mike', address:'florence ave'}]

array1.push(array2);

If you want to mutate array1 : 如果您想变异array1

array1.push.apply(array1, array2);

Otherwise: 除此以外:

var array3 = array1.concat(array2);

If you wanted to push a single object in the array, you could just reference it by it's specific index : 如果要在数组中推送单个对象,则可以通过其特定索引来引用它:

array1.push(array2[0]);

Otherwise, if you wanted to push all of the items, you might consider just concatenating them via the concat() function : 否则,如果您想推送所有项目,则可以考虑通过concat()函数将它们串联:

array1.concat(array2);

If you want to use ES6 you can use the spread operator : 如果要使用ES6,可以使用spread运算符

array1.push(...array2);

which is functionally equivalent to this ES5 method... 在功能上等效于此ES5方法...

 array1.push.apply(array1, array2);

...mentioned in one of the other answers. ...在其他答案之一中提到。

DEMO DEMO

To push {name:'Mike', address:'florence ave'} into array1 : 要将{name:'Mike', address:'florence ave'}推入array1:

array1.push(array2[0]);

As the object you want is simply the first element in your array2 variable. 由于您想要的对象只是array2变量中的第一个元素。

(var I = 0; I <= array2.length-1 ; I++){
  array1.push(array2[I])
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM