Home > Software design >  Replacing an one of the objects in an array of objects in javaScript
Replacing an one of the objects in an array of objects in javaScript

Time:08-30

I have below array and object and I am trying to replace the entire object of the array where id matches.

this.integrationActionsArray = [{id: 1, key: 'some key', value: 'some value'}]
myObject = {id: 1, key: 'another key', value: 'another value'}

so far I have made below attempts to change the one of the entire objects of an array of objects

 this.integrationActionsArray
                    .find(data => {
                        if (data.id == myId) {
                            data = myObject
                        }
                    })
console.log(this.integrationActionsArray) 

Expectation of the above log is something like below

[{id: 1, key: 'another key', value: 'another value'}]

but it is still like

[{id: 1, key: 'some key', value: 'some value'}]

I have tried using forEach, filter, map and every other iterator but still no luck.

CodePudding user response:

When you do data = myObject, what you are expecting does not happen.

data is just a local variable that points to the integrationActionsArray array element in the find callback method. Once you run the above statement, you are not changing anything in the array, instead just reassigning data.

A simple representation of what is happening above.

let data = { a : 1 , b : 2 };

let data1 = data;

data1={x : 1};
//You can not expect data to change
console.log(data);

To fix this grab the index, and then replace the element in the array.

const integrationActionsArray = [{id: 1, key: 'some key', value: 'some value'}];

const myObject = {id: 1, key: 'another key', value: 'another value'};
const myId = 1;
integrationActionsArray
                    .forEach((data,index) => {
                        if (data.id == myId) {
                            integrationActionsArray[index] = myObject
                        }
                    })
console.log(integrationActionsArray) 

Note: The above code will work with find() but find returns a specific element. And a simple forEach is ideal for the above case.

  • Related