简体   繁体   English

Lodash - 用相同的索引替换数组中的 object

[英]Lodash - replace object in array with the same index

I want to replace the object with the same ID in an array.我想用数组中的相同 ID 替换 object。 I have used.unionBy using Lodash.我已经使用了.unionBy 使用 Lodash。 The problem is the the new object appears at the the first instead of the same index.问题是新的 object 出现在第一个而不是相同的索引处。

Here is my code.这是我的代码。 Hope you can help me.希望您能够帮助我。 Thanks!谢谢!

state.allStudents is the array. state.allStudents是数组。 And the students is the new object to replace that existing object in the array with same _id学生们是新的 object 来替换阵列中具有相同 _id 的现有 object

state.allStudents = _.unionBy([students], state.allStudents, '_id');

I would use .findIndex and .splice我会使用.findIndex.splice

    let index = state.allStudents.findIndex(i => i._id === students._id);
    if (index != -1) {
        state.allStudents.splice(index, 1, students);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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