更改对象数组中的一个值

时间:2015-12-28 08:25:55

标签: javascript arrays

我有对象users的数组:

let state = {
  users: [
    {id: 1, name: 'Igor',  selected: false},
    {id: 2, name: 'Anton', selected: false},
    {id: 3, name: 'Vasya', selected: false},
    {id: 4, name: 'Pete',  selected: false},
    {id: 5, name: 'Dan',   selected: false}
  ], ....

一个适用于此对象的函数:

export function selectUser(userId) {
  if (state.users.find(item => item.id == userId).selected == false) {
    /* some code */

    //[needed] Code to update the user property selected to true

  } else {
    /* some other code */

    //[needed] Code to update the user property selected to true
  }
  emitChange();
}

如何做到这一点,不覆盖整个阵列,奇怪的是无法想到任何事情

3 个答案:

答案 0 :(得分:1)

find()方法返回要更新的对象。因此,首先调用它并将其分配给变量,然后测试它是否存在,如果是,则使用它。

export function selectUser(userId) {
  var user = state.users.find(item => item.id == userId);

  if (user != 'undefined'){
    if (user.selected == false) {
      /* some code */

      user.name = 'New Name';
      // etc

    } else {
      /* some other code */
    }
  }

  emitChange();
}

答案 1 :(得分:1)

根据真假案例中的评论,这应该有效:

attributes

答案 2 :(得分:1)

如果你想切换属性,那么

export function selectUser(userId) {
  var user = state.users.find(user => user.id == userId);
  var isSelected = user.selected; 
  // state.users.forEach(user => user.selected = false ); deselect others 
  user.selected = !isSelected;
  emitChange();
}