Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

301
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda