在javaScript中迭代后从对象数组更改单个值

问题描述 投票:-1回答:3

这是我的代码:

let user = [
    {id: 1, name: "Chris", active: "true"},
    {id: 2, name: "James", active: "true"},
    {id: 3, name: "Jeremy", active: "true"},
];

handleClick = () => {
    for(let i in user) {
        if (Object.hasOwnProperty.call(user, i)) {
                user[i].active = false;
         }
    }
};

我一直在研究许多主题,但找不到任何答案。

您可以在一次点击(handleClick)上看到,我想将active的状态从“ true”修改为“ false”,反之亦然。但是我希望这种情况仅发生在我单击的用户上,而不是全部发生。每个用户都有自己的按钮。

我开始认为也许我应该以某种方式使用id。

javascript reactjs
3个回答
0
投票

在函数中传递用户的ID,然后添加if语句

(id) =>{ user.forEach( obj =>{
 If(obj.id === id) 
obj.active = !obj.active;
})} 

0
投票

这里是解决方法:

enter code here
let user = [
    {id: 1, name: "Chris", active: "true"},
    {id: 2, name: "James", active: "true"},
    {id: 3, name: "Jeremy", active: "true"},
];

handleClick = id => {
    user.forEach( obj => {
      if(obj.id === id) 
     obj.active = !obj.active;
    });
};

0
投票

如果尝试使用ES6,也要使用boolean来处理此功能,您应该在不使用truefalse的情况下写quotationdouble-quotation

let user = [{
    id: 1,
    name: "Chris",
    active: true
  },
  {
    id: 2,
    name: "James",
    active: true
  },
  {
    id: 3,
    name: "Jeremy",
    active: true
  },
];

function handleClick(id) { // handleClick = (id) => {
  const result = user.map(obj =>
    obj.id === id ? { ...obj,
      active: !obj.active
    } : obj
  )
  console.log(result)
}
<div onclick="handleClick(1)">Click</div>

<!-- React version -> <div onClick="this.handleClick(id)">Click</div> -->
© www.soinside.com 2019 - 2024. All rights reserved.