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

How to get the key of json

(*-*)浩
(*-*)浩Original
2019-05-20 11:04:3514882browse

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

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!

Statement:
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
Previous article:Is nodejs a js framework?Next article:Is nodejs a js framework?