Home > Back-end >  Javascript how to return data from object with matching key
Javascript how to return data from object with matching key

Time:02-19

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?

CodePudding user response:

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

  • Related