2017-05-07 58 views
1

我總是依賴於lodash和splice的findIndex重新提交我的更新數據,我正在尋找溝通lodash,因爲我正在與babel編譯現在,可以做些什麼來改善下面的代碼?在es6 lodash的findIndex我

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

回答

0

這裏是一個班輪:

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

這是刪除項目,我想拼接它不會刪除它。 –

+0

在這種情況下:'this.users = this.users.map(oldUser => oldUser.id === user.id?user:oldUser);' –

+0

因此findIndex和splice是無用的嗎? –

1

您可以將您的用戶存儲在Map從用戶ids到用戶而不是數組。那麼你只需要寫

this.users.delete(user.user_id); 

這也會加快你的查找時間。

+0

商店用戶的地圖?那是什麼? –

+0

我想替換更新的項目,而不是刪除它。 –

+0

@Alan然後使用'.set()'。對於這些類型的操作,映射比數組快(恆定時間而不是線性)。你可以在這裏找到Map的文檔:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map –

1

JS數組也有一個findIndex方法是有用的:

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