Home > Web Front-end > JS Tutorial > How to get the key of json

How to get the key of json

(*-*)浩
Release: 2020-09-19 13:43:41
Original
15001 people have browsed it

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 ){}".

How to get the key of json

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
Copy after login

1. Use a for loop

for (var key in json) {
    console.log(key);     //获取key值
    console.log(json[key]); //获取对应的value值
}
Copy after login

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))
Copy after login

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
});
Copy after login

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!

Related labels:
js
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