简体   繁体   中英

Lodash - replace object in array with the same index

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');

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM