0
[{_id: "5f7ab0e57b4d3030cc14181b", Name: "Child Support", pic: "https://i.ibb.co/f8bBB8L/food-Charity.png", description: "Lorem ipsum", eventStarts: "20-04-2020"}, {_id: "5f7ab0e57b4d3030cc14181c", Name: "Refuge Shelter", pic: "https://i.ibb.co/7nrP5Vg/babySit.png", description: "Lorem ipsum", eventStarts: "20-01-2020"}, {_id: "5f7ab0e57b4d3030cc14181d", Name: "Food Charity", pic: "https://i.ibb.co/rmkjNyp/bird-House.png", description: "Lorem ipsum", eventStarts: "25-04-2020"}]

how can i find an array with an _id name such as "5f7ab0e57b4d3030cc14181c"?

I need to get to the name of that array... Using react and MongoDB. specificEvents = _id ... So i want to use it to find an array and get the name.

const Register = () => {
    const [loggedInUser, setLoggedInUser] = useContext(UserContext);
    const { specificEvent } = useParams();
    const [events, setevents] = useState({})

    useEffect(() => {
        fetch('http://localhost:3100/events')
            .then(res => res.json())
            .then(data => {
                setevents(data);

///////// I wanted my finding code here ///////////

            })
    }, [])
  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – corashina Oct 06 '20 at 07:34

3 Answers3

0

You could use a find method of an array. The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

data.find(d => d._id === idToBeSearched);
Prateek Thapa
  • 4,829
  • 1
  • 9
  • 23
0

It may work,

data.map(data => ({
   if(data._id =="5f7ab0e57b4d3030cc14181c"){
     alert('You can do the rest')
   }
}));

or if it not work you can stringify the data -

var find = JSON.stringify(data);
find.map(data => ({
   if(data._id =="5f7ab0e57b4d3030cc14181c"){
     alert('You can do the rest')
   }
}));

Hope it will solve your problem.

0

Solved it by doing this...

const { specificEvent } = useParams();
    const [events, setevents] = useState({})

    useEffect(() => {
        fetch('http://localhost:3100/events')
            .then(res => res.json())
            .then(data => {
                setevents(data);
            })
    }, [])


    let getName = {};
    for (let i = 0; i < events.length; i++) {
        const { _id } = events[i];
        if (_id === specificEvent) {
            getName = events[i];
        }
    }
    const { Name } = getName;