简体   繁体   English

es6中lodash的findIndex

[英]findIndex of lodash in es6

I always depends on findIndex of lodash and splice to rerender my updated data, I'm looking to ditch lodash as I'm compiling with babel now, what can be done to improve below code? 我始终依靠lodash和splice的findIndex来重新渲染更新后的数据,现在我正在抛弃lodash,因为我现在正在使用babel进行编译,如何改进下面的代码?

onDoneUpdatedUserStatus(user) {

    //this.users means existing array of object of existing users

    const index = findIndex(this.users, { user_id: user.user_id });
    if (index > -1) {
        this.users.splice(index, 1, user);
    }
}

You can store your users in a Map from user ids to users instead of an array. 您可以将用户从用户ID到用户(而不是数组)存储在Map Then you just need to write 那你只需要写

this.users.delete(user.user_id);

This will also speed up your lookup time. 这也将加快您的查找时间。

JS Array also has a findIndex method which is useful: JS Array还有一个findIndex方法,该方法很有用:

onDoneUpdatedUserStatus(user) {
    const index = this.users.findIndex(u => u.user_id === user.user_id);
    if (index > -1) {
        this.users.splice(index, 1, user);
    }
}

这里是单线:

this.users = this.users.map(oldUser => oldUser.id === user.id ? user : oldUser);

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

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