0

I want to replace the object with the same ID in an array. I have used .unionBy using Lodash. The problem is the the new object appears at the the first instead of the same index.

Here is my code. Hope you can help me. Thanks!

state.allStudents is the array. And the students is the new object to replace that existing object in the array with same _id

state.allStudents = _.unionBy([students], state.allStudents, '_id');
2
  • can you add an example? Commented Jun 22, 2020 at 13:36
  • Why downvote? The question was clearly asked and he offered enough information to solve and he showed us what he trried. Commented Jun 22, 2020 at 18:40

1 Answer 1

1

I would use .findIndex and .splice

    let index = state.allStudents.findIndex(i => i._id === students._id);
    if (index != -1) {
        state.allStudents.splice(index, 1, students);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

I'm guessing that you are using vuex. If so, this has the added benefit of maintaining reactivity.

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.