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

298
Visualizações
How to add input value as a tag to an object array and display it in react js

How can I add a key value to an object array? I'm Fetching an api and want to add value to a particular student/person array from user's input. Let's say we click on the first list's input and we type xyz the it should add a tag: 'xyz' and then if we add abc then it has to be tag: ['xyz', 'abc'].Im toatlly new to react so pardon me if somethings terribly wrong.

import React from "react";
import "./App.css";
export default class FetchRandomUser extends React.Component {


  state = {
    loading: true,
    people: [],
    input: '',
  }

  async componentDidMount() {
    const url = "https://api.hatchways.io/assessment/students";
    const response = await fetch(url);
    const data = await response.json();
    this.setState({ people: data.students, loading: false });
    //
  }

  onChangeHandler(e) {
    this.setState({
      input: e.target.value,
    })
  }

  render() {
    if (this.state.loadin) {
      return <div>loading...</div>;
    }

    if (!this.state.people.length) {
      return <div>didnt get person...</div>;
    }

    const list = this.state.people.filter(person => this.state.input.toLowerCase() === '' || person.firstName.toLowerCase().includes(this.state.input.toLowerCase()) || person.lastName.toLowerCase().includes(this.state.input.toLowerCase()))
    .map(person => (
      <div key={person.id}>
        <li>
          {JSON.stringify(person.firstName)}
          {JSON.stringify(person.lastName)}
          {/*want to add newTag value for particular person in list */}
          <input type="text" />
          {/* and display it here */}
        </li>
      </div>
    ));

    return (
      <div>
        <div className="example1">
          {/* this input will search and filter person based on first and last name */}
          <input value={this.state.input} type="text" onChange={this.onChangeHandler.bind(this)} />
          <ul>{list}</ul>
        </div>
      </div>
    )
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In case I understand your question correctly, this is one of the ways that you can add a key value to your object:

var obj ={ a: 1, b: 2 };
obj.c = 5  
console.log(obj);
output  
Object { a: 1, b: 2, c: 5 }

since you want to do this for a specific student, there should be a logic to find the correct student first. so you have to loop over your students array.

const data = [your array]
const updatedData = data.map(student =>{
if (student.id === person.id) {// you need to use the correct key names here
student = {... student,
 tag: "xyz" // this xyz comes from you input, you need to adjust here
}
}
return student
})

after that you can render correct data. Keep in mind, I just wrote how to update an array just one time. Since you are using react, you need to apply this logic to update your state. So every-time there is an update, also state should get updated.

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