Below, the editor will introduce to you how to find a specified single piece of data based on JS. The specific method is as follows:
In general, we will require the backend to output a bunch of JSON data of the list to us when it is on the list, and then we loop through the pile of data to display the list on the frontend.
When we are on the content page, we require the output of JSON data of the content page to us, and we can make the content page.
However, sometimes, the data is not particularly complicated, and we may need to specify a single piece of data from the data in the list. How to do it?
Standard answer, find method
var json = [{"id":1,"name":"Zhang San"},{"id":2,"name":"Li Si"},{"id":3,"name":"Wang Wu"}];As shown above, json is a typical list data. How do I specify that this piece of data with ID=1 be found?
var data = json.find(function(e){return e.id == 1});console.log(data);Through such a callback function, you can find a single piece of data in the list data.
This code uses a find method and uses a callback function. This problem is elegantly solved. Below, I will give my original solution.
My plan, for loop
The find method above is the solution I found through search engines, click here: Array.prototype.find() . And my original solution is as follows:
var json = [{"id":1,"name":"Zhang San"},{"id":2,"name":"Li Si"},{"id":3,"name":"Wang Wu"}];var data = getJsonById(2,json);function getJsonById(id,data){for (var i = 0; i < data.length; i++) {if (data[i].id==id) {return data[i];}};}The principle is very simple. By looping through traversal, find the same content as the conditions, and then return it.
The above content is the method of finding a specified single piece of data from a set of data introduced by the editor. I hope it will be helpful to everyone!