Add object with same key in vuejs

744 views Asked by At

I'm using vuejs and laravel. In component, i have:

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

After fetching, i have this. I want to load more data if user scroll, so i have to add new object into data.

I tried Object.assign, push... but the properties had be overwritten. I also loop the data and add new object but not work either...

I want something like:

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

Any idea? Tks!

2

There are 2 answers

1
Hassan Imam On BEST ANSWER

You can extract the values from the object using Object.values(), then join both of the values using array#concat then using Object.assign() create your object.

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

You can also use array#reduce instead of 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);

1
santanu bera On
data:function(){
   return {
     data: []
   }
}

Now you can add element either by

this.data.push(object);

or You can concat another array like this -

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

After Updating the question -

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