Home > Article > Web Front-end > jquery json array modification
In front-end development, we often encounter scenarios where JSON arrays need to be modified and manipulated. jQuery can help us achieve this very well. This article will introduce how to use jQuery to modify JSON arrays.
First, we need to get the JSON array. We can directly define a JSON array, or obtain the JSON array returned by the server through an Ajax request.
Suppose we have obtained the following JSON array from the server:
var users = [ { "name": "张三", "age": 20, "gender": "male" }, { "name": "李四", "age": 25, "gender": "female" }, { "name": "王五", "age": 30, "gender": "male" } ];
We can traverse the JSON Array and find the element to be modified based on the condition.
The following example demonstrates how to change the age of a user who is 25 years old to 30 years old:
$.each(users, function(index, user) { if(user.age === 25) { user.age = 30; } });
We can add new elements to the JSON array through the push() method.
The following example demonstrates how to add a new user to the JSON array:
var newUser = { "name": "赵六", "age": 28, "gender": "male" }; users.push(newUser);
We can iterate through JSON array, find the element to be deleted based on the conditions, and then delete the element from the JSON array through the splice() method.
The following example demonstrates how to delete users aged 25 years old:
$.each(users, function(index, user) { if(user.age === 25) { users.splice(index, 1); } });
After modifying the JSON array After that, it usually needs to be sent to the server, processed and then returned. At this point, we need to convert the JSON array into a JSON string.
You can use the JSON.stringify() method to convert a JSON array into a JSON string:
var usersString = JSON.stringify(users);
If we get a JSON string from the server, we need to convert it into a JSON array before we can modify it.
You can use the JSON.parse() method to convert a JSON string into a JSON array:
var usersString = '[{"name":"张三","age":20,"gender":"male"},{"name":"李四","age":25,"gender":"female"},{"name":"王五","age":30,"gender":"male"}]'; var users = JSON.parse(usersString);
The above is how to use jQuery to modify a JSON array. Through the above operations, we can easily modify and operate JSON arrays, thereby achieving more flexible front-end development.
The above is the detailed content of jquery json array modification. For more information, please follow other related articles on the PHP Chinese website!