JS finds a specified single data record from a group of data, and js returns a single record.

Source: Internet
Author: User

JS finds a specified single data record from a group of data, and js returns a single record.

The following section describes how to find a specified single piece of data from a group of data based on js. The specific method is as follows:

In general, we will require the back-end to output a bunch of JSON data in the list, and then we will loop the data to display the list on the front end.

When we are on the Content Page, We need to output the JSON data of a content page to us so that we can create a content page.

However, sometimes the data is not very complex. We may need to specify a single piece of data from the List data. How can this problem be solved?

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 to find the data with ID = 1?

var data = json.find(function(e){return e.id == 1});console.log(data);

With this callback function, you can find a single piece of data in the list.

This Code uses a find method and a callback function. It solves this problem elegantly. below, I will provide my original solution.

My solution, for Loop

The above find method is a solution I found through the search engine. Click here: Array. prototype. find (). My original solution is as follows:

Var json = [{"id": 1, "name": "Zhang San" },{ "id": 2, "name": "Li Si "}, {"id": 3, "name": ""}]; 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. You can find the content consistent with the condition through loop traversal, and then return it.

The above content is a small series of JS methods for finding a specified single piece of data from a group of data, I hope to help you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.