0

I have a Object named objectX like this

{
    "test": [
      {
        "id": "de6b4d1c-6e04-46a1-908b-9ed5c78e1boc", 
      }, 
      {
        "id": "de6b4d1c-6e04-46a1-908b-9ed5c78e1boc", 
      }, 
      {
        "id": "de6b4d1c-6e04-46a1-908b-9ed5c78e1boc", 
      }, 
      {
        "id": "de6b4d1c-6e04-46a1-908b-9ed5c78e1boc", 
      }, 
      {
        "id": "de6b4d1c-6e04-46a1-908b-9ed5c78e1boc", 
      }, 
      {
        "id": "de6b4d1c-6e04-46a1-908b-9ed5c78e1boc", 
      }
    ], 
}

and i want to update the id for all my objects in my test array.

To do that, i was doing

    objectX.test.forEach((obj) => {
      obj.id = newId
    })

But with my forEach, i have this

Error: "[vuex] do not mutate vuex store state outside mutation handlers."

Anyone know how can i update my ids without getting error like this ?

1
  • 2
    Given that you are using vuex, you probably have to show a more complete example of your code, because you are not actually asking about JavaScript itself but how to do this in the context of that library. Commented Jul 28, 2021 at 9:16

1 Answer 1

1

You can't update inside a forEach, because you are updating the copy of the object and not the object itself. You can instead map over your array and return the updated array to another variable:

const objectX = {
  test: [{ name: 'a', id: 4 }, { name: 'b', id: 2 } ],
 };
const newId = 1;
objectX.test = objectX.test.map((obj) => {
  return {
     ...obj,
     id: newId,
    }
 });
 console.log(objectX.test);

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.