【问题标题】:How to find an array from array of arrays using a value?如何使用值从数组数组中查找数组?
【发布时间】:2020-10-06 04:35:32
【问题描述】:
[{_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"}]

如何找到具有 _id 名称的数组,例如“5f7ab0e57b4d3030cc14181c”?

我需要得到那个数组的名字... 使用反应和 MongoDB。 specificEvents = _id ...所以我想用它来查找数组并获取名称。

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 ///////////

            })
    }, [])

【问题讨论】:

标签: arrays search


【解决方案1】:

您可以使用数组的查找方法。 find() 方法返回提供的数组中满足提供的测试功能的第一个元素的值。

data.find(d => d._id === idToBeSearched);

【讨论】:

    【解决方案2】:

    它可能会起作用,

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

    或者如果它不起作用,您可以对数据进行字符串化 -

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

    希望它能解决你的问题。

    【讨论】:

      【解决方案3】:

      这样做解决了...

      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-21
        • 1970-01-01
        • 2021-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多