【问题标题】:Change a single value from an array of objects after iterating in javaScript在 javaScript 中迭代后更改对象数组中的单个值
【发布时间】:2020-01-11 12:03:58
【问题描述】:

这是我的代码:

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) 时看到的那样,我想将活动状态修改为“真”到“假”,反之亦然。但我希望这只发生在我点击的用户身上,而不是所有用户身上。每个用户都有自己的按钮。

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

【问题讨论】:

  • 这是来自 ReactJS 应用程序吗? handleClick函数是怎么调用的?
  • 是的,先生 :) 但我不想把整个事情都说完。我更喜欢从 JS 开始,然后去适应。
  • 我问过这个问题是因为user 数组中的元素如何与 DOM 元素相关联很重要。
  • 好的,我明白了!让我在我的代码中进行一些排序并删除需要的内容:)
  • 请使用代码 sn-p 或 jsfiddle 发布一个工作示例。

标签: javascript reactjs


【解决方案1】:

如果您尝试使用boolean,也应使用ES6 处理此功能,您应该编写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> -->

【讨论】:

  • @JeremyBertin 很高兴为您提供帮助,请选择解决您问题的最佳答案作为已接受答案或+1投票!(这是您的选择!)
【解决方案2】:

解决办法如下:

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;
    });
};

【讨论】:

    【解决方案3】:

    我看到你使用了,所以你正在寻找的是这样的:

    handleClick = id => {
      let arr = this.state.users.map(user => {
        let u = { ...user };
    
        if(u.id === id) {
          u.active = !u.active;
        }
    
        return u;
      });
    
      this.setState({ users: arr });
    }
    

    看看这个演示:

    let users = [
      {id: 1, name: "Chris", active: true}, 
      {id: 2, name: "James", active: false}, 
      {id: 3, name: "Jeremy", active: true}
    ];
    
    class Demo extends React.Component {
        state = { users };
        
        colorize = active => active ? 'green' : 'red';
        
        handleClick = id => {
          let arr = this.state.users.map(user => {
            let u = { ...user };
            
            if(u.id === id) {
              u.active = !u.active;
            }
            
            return u;
          })
          
          this.setState({ users: arr });
        }
        
        render (){
            return (
             <div>
               {this.state.users.map(user => (
                <div key={user.id} className="row">
                  <p className="user">{user.name}</p>
                  <p className={`status ${this.colorize(user.active)}`}>
                    {user.active.toString()}
                  </p>
                  <button 
                    onClick={() => this.handleClick(user.id)}>
                    Change status
                  </button>
                </div>
               ))}
             </div>
            );
        }
    }
    ReactDOM.render(<Demo />, document.getElementById('app'));
    .row {
      display: flex;
      flex-direction: row;
    }
    
    .user {
      font-weight: bold;
    }
    
    .user::after {
      content: ":";
    }
    
    .status {
      margin-left: 10px;
    }
    
    button {
      margin: 15px 5px 5px 5px;
      border-radius: 10px;
    }
    
    .red { 
      color: red;
    }
    
    .green {
      color: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="app"></div>

    【讨论】:

    • 感谢您的帮助 :) 问题已经解决了,但采用不同的方法总是很好。
    【解决方案4】:

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

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

    【讨论】:

    • 该死的。这看起来很棒!马上去试试这个:)
    • @JeremyBertin 很高兴我能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2018-08-18
    • 1970-01-01
    • 2017-03-29
    • 2019-02-27
    • 2014-08-31
    相关资源
    最近更新 更多