在vuejs中添加具有相同键的对象
Add object with same key in vuejs
我正在使用 vuejs 和 laravel。
在组件中,我有:
data(): {
return {
data: []
}
}
抓取后,我有this。
如果用户滚动,我想加载更多数据,所以我必须将新对象添加到数据中。
我尝试了Object.assign、push...但属性已被覆盖。
我也循环数据并添加新对象但也不起作用...
我想要这样的东西:
obj1 = {0: value1, 1: value2};
obj2 = {0: value3, 1: value4};
=> obj = {0: value1, 1: value2, 3: value3, 4: value4};
有什么想法吗?谢谢!
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);
您可以使用 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);
我正在使用 vuejs 和 laravel。 在组件中,我有:
data(): {
return {
data: []
}
}
抓取后,我有this。 如果用户滚动,我想加载更多数据,所以我必须将新对象添加到数据中。
我尝试了Object.assign、push...但属性已被覆盖。 我也循环数据并添加新对象但也不起作用...
我想要这样的东西:
obj1 = {0: value1, 1: value2};
obj2 = {0: value3, 1: value4};
=> obj = {0: value1, 1: value2, 3: value3, 4: value4};
有什么想法吗?谢谢!
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);
您可以使用 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);