Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - How to filter the same id as the URL Params?

I have a mock database that looks like this

[
  {
    "id": 1,
    "jobTitle": "Budget/Accounting Analyst III",
    "companyName": "Topiclounge",
    "city": "Duluth",
    "state": "Minnesota",
    "country": "United States",
    "jobDescription": "egestas metus aenean fermentum donec ut mauris eget massa tempor convallis nulla neque libero convallis eget eleifend luctus ultricies eu nibh quisque id justo sit amet sapien dignissim vestibulum vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae nulla dapibus dolor vel est donec odio justo sollicitudin ut suscipit a feugiat et eros",
    "datePosted": "1/23/2020"
  }, 
...
]

and so on.

I want to retrieve the object with the id that matches the id from the urlParams which I am getting from useParams(); I am using this axios.get request

const getJobById = async () => {
    try {
      const response = await Axios.get(`https://api.jsonbin.io/b/5ff798661d107958ae4ca82b`)
      console.log(response.data, id)
      const job = response.data.filter(item => item.id === id)[0]
      console.log(job)
    } catch (error) {
      console.log(error)
    }
  }

To retrieve data from the mock api and to filter out the object that matches this id, however I am getting an undefined from console.log(job) How can i filter this data in the correct way?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use response.data.find(item => item.id === id) instead but that is likely not going to fix your problem.

To be able to further assist you, could you please share what this line prints into the console:

console.log(response.data, id)

Based on the OP's response in the comments below, the problem is that === is also checking for the same type. Since the variable id is a String and the value of the id key in the object of the api output is a Number item.id === id will always return false. You could either just use == in this case or you should convert the String id to a Number: id = Number(id).

Or just what the OP actually did to solve it:

item.id === parseInt(id)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...