Home > Article > Web Front-end > Detailed explanation of the sample code for javascript to traverse the key of a json object and any js object attribute (picture)
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);
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);
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));
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!