Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!