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

130
Vistas
Javascript how to return data from object with matching key

I have an array of objects each with name, height and mass. I have a component that gets the names and displays them to the browser. What I'm trying to do is, in a separate component, get the height and mass that correlates to each name.

For example I have:

[
   {name: 'Luke Skywalker', height: '172', mass: '77'},
   {name: 'C-3PO', height: '167', mass: '75'}
]

I should mention I'm using react for this project. My Component is below:

export default function Character(props) {
    const [charStats, setCharStats] = useState("");
    const [currentName, setCurrentName] = useState("");
    const { name } = props;

    useEffect(() => {
        axios.get(`${BASE_URL}`)
        .then(res => {
            setCharStats(res.data);
            setCurrentName(name);
        })
        .catch(err => console.error(err))
    }, [])

    return (
        <div>
            <div>{ name }</div>
            <button>Stats</button>
            { name === currentName ? charStats.map(char => {
                return <Stats height={char.height} mass={char.mass} key={char.name} />;
                }) : <h3>Loading...</h3>
            }
        </div>
    )
}

The name prop I am getting from another component, I can console.log it and get each individual name so I know that works. But with the code above, I am getting the height and mass of every object returned instead of just the ones that match the name. How can I get specifically the height and mass of each object?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Looks like you might want to call filter before using map, like for example: data.filter(x => x.name === name).map(char => {.... which returns a collection that only contains the elements that match the condition). Or if you only want to find one element, its better to use .find(x => x.name === name) instead

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