How to replace a specific object in an array in javascript?

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?

+4
3

extend findWhere. , , :

_.extend(_.findWhere(users, { userId: updatedUser.userId }), updatedUser);

, .

" , ", - , (, API).

+18

, indexOf , .

indexOf findIndex

:

_.indexOf, , ; -1.

_.findIndex([4, 6, 8, 12], isPrime);
=> -1 // not found
_.findIndex([4, 6, 7, 12], isPrime);
=> 2

, - :

var indexOfUpdatedUser = _.findIndex(users, { userId: updatedUser.userId });
users[indexOfUpdatedUser] = updatedUser;

: -1, , (.. )

+2

Instead of an array, an object with identifiers as property names would be simpler:

var users = {
  23: {userName: "foo"},
  34: {userName: "wrong"},
  45: {userName: "baz"},
  56: {userName: "..."}
};

Then, to update some users’s data, simply use

users[updatedUserId] = updatedUserData;
+1
source

Source: https://habr.com/ru/post/1540443/


All Articles