0

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.

2
  • Can you clarify which final array structure/values you require? Commented Aug 29, 2022 at 16:31
  • I am expecting [{id: 1, key: 'another key', value: 'another value'}] Commented Aug 29, 2022 at 16:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.