Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading