Home » vue » How to update or add object inside arrray in vue JS 2?

How to update or add object inside arrray in vue JS 2?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have item list like below. I want to add new items to the list but if the id is same I want to change the value of object.

For Example :

segmentValues: [
    {
        id:1,
        value:'Foo'
    },
    {
        id:2,
        value: 'Boo'
    }
],

segmentValues.push({id: 2, value:'Gogo'});

Now I’m pushing this new item but items list already has id = 2, so it should replace the value like below:

segmentValues: [
    {
        id:1,
        value:'Foo'
    },
    {
        id:2,
        value: 'Gogo'
    }
],

How Can I do this in vuejs ?

Answers:

Check if id exists in array before push:

var obj = {id: 2, value:'Gogo'};
var objInArray = segmentValues.find(x => x.id === obj.id);

if (objInArray){
    objInArray = obj;
} else {
    segmentValues.push(obj);
}