I have an array of users, and I'd like to update one of those users.
users = [
{userId: 23, userName:"foo"},
{userId: 34, userName:"wrong"},
{userId: 45, userName:"baz"}
{userId: 56, userName:"..."},
]
updatedUser = {
userId: 34,
userName: bar
}
I'm using underscorejs. I thought the simplest way is to find the index of the user to be updated, and then just set the value of that user to my updated value. Unfortunately, underscore's indexOf function doesn't accept properties, only values. To use it, I'd have to first user findWhere and then pass what that returns into indexOf:
var valueOfUpdatedUser = _.findWhere(users, { userId: updatedUser.userId })
var indexOfUpdatedUser = _.indexOf(users, valueOfUpdatedUser)
users[indexOfUpdatedUser] = updatedUser;
A second approach would be to use reject to remove the matched user, and then push my updated user to the array.
Surely there's a better, simpler way?
usersas an object and useuserIdas keys.users = { 23: { userName: 'foo' }, 34: { userName: 'wrong' }};. That makes updating very easy:users[34].userName = 'bar';.23: { userinfo here }, 34: { another userinfo here }. In this case replace code will be just users[%id%] = { new info here };