首页 > 解决方案 > 在 vuejs 中添加具有相同键的对象

问题描述

我正在使用 vuejs 和 laravel。在组件中,我有:

data(): {
   return {
     data: []
   }
}

取完后,我有这个。如果用户滚动,我想加载更多数据,所以我必须将新对象添加到数据中。

我试过Object.assignpush ...但属性已被覆盖。我也循环数据并添加新对象但也不起作用......

我想要类似的东西:

obj1 = {0: value1, 1: value2};
obj2 = {0: value3, 1: value4};
=> obj = {0: value1, 1: value2, 3: value3, 4: value4};

任何的想法?谢!

标签: objectvue.jsadd

解决方案


data:function(){
   return {
     data: []
   }
}

现在您可以通过以下方式添加元素

this.data.push(object);

或者您可以像这样连接另一个数组 -

this.data = this.data.concat(anotherArray);

更新问题后 -

/* For the case in question, you would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects you can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */

let obj = Object.assign({}, obj1, obj2, obj3, etc);

推荐阅读