Home > Web Front-end > JS Tutorial > Detailed explanation of the sample code for javascript to traverse the key of a json object and any js object attribute (picture)

Detailed explanation of the sample code for javascript to traverse the key of a json object and any js object attribute (picture)

黄舟
Release: 2017-03-21 14:38:14
Original
2033 people have browsed it

The following editor will bring you an articlejavascriptTraverse the key of the json object and any js object attribute instance. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

Use the keys method to obtain the properties and methods of the object:

 function Pasta(grain, width, shape) {
        this.grain = grain;
        this.width = width;
        this.shape = shape;
        this.toString = function () {
          return (this.grain + ", " + this.width + ", " + this.shape);
        }
      }
      
      var spaghetti = new Pasta("wheat", 0.2, "circle");
      var arr = Object.keys(spaghetti);
      document.write(arr);
Copy after login

Result picture:

Displays the names of all enumerable properties starting with the letter "g" in the Pasta object:

function Pasta(grain, width, shape) {
        this.grain = grain;
        this.width = width;
        this.shape = shape;
      }

      function CheckKey(value) {
        var firstChar = value.substr(0, 1);
        if (firstChar.toLowerCase() == "g") {
          return true;
        } else {
          return false;
        }
      }

      var polenta = new Pasta("corn", 1, "mush");
      var keys = Object.keys(polenta).filter(CheckKey);
      document.write(keys);
Copy after login

The result is as shown:

Traverse the keys of the json object:

var an_obj = { 100: 'a', 2: 'b', 7: 'c', "name": "wu", "interesting": "Game" };
 document.write(Object.keys(an_obj));
Copy after login

The result is as shown:


The above is the detailed content of Detailed explanation of the sample code for javascript to traverse the key of a json object and any js object attribute (picture). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template