在Vue.js中使用相同的键添加对象

时间:2018-06-27 04:35:24

标签: object vue.js add

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

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

获取后,我有this。 如果用户滚动,我想加载更多数据,所以我必须向数据中添加新对象。

我尝试了 Object.assign ...,但是属性已被覆盖。 我还循环数据并添加新对象,但也不起作用...

我想要类似的东西

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

有什么主意吗?谢谢!

2 个答案:

答案 0 :(得分:0)

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);

答案 1 :(得分:0)

您可以使用Object.values()从对象中提取值,然后使用array#concat连接两个值,然后使用Object.assign()创建对象。

const obj1 = {0: 'value1', 1: 'value2'},
      obj2 = {0: 'value3', 1: 'value4'},
      result = Object.assign({}, Object.values(obj1).concat( Object.values(obj2)));
console.log(result);

您也可以使用array#reduce代替Object.assign

const obj1 = {0: 'value1', 1: 'value2'},
      obj2 = {0: 'value3', 1: 'value4'},
      result = Object.values(obj1).concat( Object.values(obj2)).reduce((r,v,i) => (r[i] = v, r), {});
console.log(result);