Home > Article > Web Front-end > How to get the key of json
Methods to obtain the key of JSON: 1. Use a for loop to directly obtain the key value in JSON; 2. Use the jquery callback function each to obtain it, with the syntax such as "$.each(array name, function(i ){}".
This article introduces how jQuery obtains the key in the json object. I hope you will gain something from reading this article and help you. Have a deeper understanding of jQuery.
For example, there is a json
var json = {"name" : "Tom", "age" : 18}; 想分别获取它的key 和 value
1. Use a for loop
for (var key in json) { console.log(key); //获取key值 console.log(json[key]); //获取对应的value值 }
2. The jquery callback function each completes
each() method specifies the function to be run for each matching element.
Tip: Returning false can be used to stop the loop early.
Syntax
$(selector).each(function(index,element))
Parameters: function(index,element)
Required. Specifies the function to run for each matching element.
index - the index position of the selector.
element - the current element (the "this" selector can also be used).
$.each(json, function(i) { console.log(i); //获取键值 console.log(json[i]); //获取对应的value });
console.log, simple science on the role of this function. Front-end Developers can call console.log in any part of the js code, and then you can see the value of the variable or expression you specified at the moment the function is called in the browser's developer console.
The above is the detailed content of How to get the key of json. For more information, please follow other related articles on the PHP Chinese website!