Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
How to set multiple object value with special key on react js

i need your help to set the new value in multiple object. I had object like this:

constructor(props){ 
 this.state = {   
  objData : [{
    score:{q1:null,q2:null,q3:null},
    data:{id:123, name:"Steven CHS"}
    },
    {
    score:{q1:null,q2:null,q3:null},
    data:{id:124, name:"Christian"}
    },
  ]
 }
}

and i would like to change the value by key q1,q2, anda q3. When i tried to use destructor like this, it's not working.

const handleChangeScore = (e,type,id) =>{
      const cScore = e.target.value;  
      this.setState((state) => {
          return {
              objData: state.objData.map((item) => {
              if(item.data.id !== e.target.name) return item;
              else return {...item.score.q1, cScore};
            })
          };
      });
}

this is the JSX where handleChangeScore() is used:

this.state.objData .map((v,index)=>(
    <tr>
        <td>{index+1}</td>
        <td>{v.data.id} - {v.data.name}</td>
        <td><input type="text" name={v.data.id} className="form-control" onChange={(e)=>handleChangeScore(e,"q1",v.data.id)} defaultValue={(v.score.q1) ? v.score.q1 : 0} /></td>
        <td><input type="text" name={v.data.id} className="form-control" onChange={(e)=>handleChangeScore(e,"q2",v.data.id)} defaultValue={(v.score.q2) ? v.score.q2: 0} /></td>
    </tr>                                                
))

The problem is when i use destructor to change the value on multiple object with specific key its not work or not change the value. Can anyone help me to fix my code ? Here's the full code in codesanbox

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Few things to be fixed

  1. Your item.data.id is number and e.target.name is string. To compare them without type comparison use != instead of !==.

  2. The else block should be corrected as below.

  handleChangeScore = (e, type, id) => {
    const cScore = e.target.value;
    this.setState((state) => {
      return {
        ...state,
        objData: state.objData.map((item) => {
          if (item.data.id != e.target.name) return item;
          else {
            return { ...item, score: { ...item.score, [type]: cScore } };
          }
        })
      };
    });
  };

Code Sandbox

about 4 years ago · Juan Pablo Isaza Relatório

0

Try below code no need to use map(). just pass the index in this.handleChangeScore() function !

And put handleChangeScore() this function in outside of render() !

export class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      objData: [
        {
          score: { q1: null, q2: null, q3: null },
          data: { id: 123, name: "Steven CHS" }
        },
        {
          score: { q1: null, q2: null, q3: null },
          data: { id: 124, name: "Christian" }
        }
      ]
    };
  }

  handleChangeScore = (value, index, childObj) => {
    this.state.objData[index].score[childObj] = value;
    this.setState(this.state);   
  };

  render() {
    return (
      <div className="App">
        <table border="1">
          {this.state.objData.map((v, index) => (
            <tr>
              <td>{index + 1}</td>
              <td>
                {v.data.id} - {v.data.name}
              </td>
              <td>
                <input
                  type="text"
                  name={v.data.id}
                  className="form-control"
                  onChange={(e) => this.handleChangeScore(e.target.value, index, "q1")}
                  defaultValue={v.score.q1 ? v.score.q1 : 0}
                />
              </td>
              <td>
                <input
                  type="text"
                  name={v.data.id}
                  className="form-control"
                  onChange={(e) => this.handleChangeScore(e.target.value, index, "q2")}
                  defaultValue={v.score.q2 ? v.score.q2 : 0}
                />
              </td>
            </tr>
          ))}
        </table>
      </div>
    );
  }
}

export default App;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda