I have an array of users and I would like to update one of these users.
users = [
{userId: 23, userName:"foo"},
{userId: 34, userName:"wrong"},
{userId: 45, userName:"baz"}
{userId: 56, userName:"..."},
]
updatedUser = {
userId: 34,
userName: bar
}
I am using underscorejs. I thought the easiest way is to find the user index for the update, and then just set the value of this user for my updated value. Unfortunately, the underscore function indexOf does not accept properties, but only values. To use it, I would have to first findWhere , and then pass what is returned to indexOf:
var valueOfUpdatedUser = _.findWhere(users, { userId: updatedUser.userId })
var indexOfUpdatedUser = _.indexOf(users, valueOfUpdatedUser)
users[indexOfUpdatedUser] = updatedUser;
The second approach was to use reject to remove the consistent user, and then direct my updated user to an array.
Of course, is there a better, easier way?