The examples in this article describe the adding, deleting and sorting methods of json format data. Share it with everyone for your reference, the details are as follows:
JS data format and json data format each have their own uses. Personally speaking, json is more useful, as js itself has more restrictions on arrays and objects.
Take js array as an example:
var a = ['1']; a[5] = 52; a.length //这儿的结果是6,也就是说,中间的key会自动补全,而值呢,是undefined
1. Add and delete
1. One-dimensional array
test = {}; //空json对像 test['firstname'] = "tank"; //添加二个元素 test['lastname'] = "zhang"; console.log(test); //查看 delete test['lastname']; //删除json中的某个元素 console.log(test);
2. Two-dimensional array
test1 = [{"name":"tank","total":"100"},{"name":"zhang","total":"23"},{"name":"hao","total":"325"}]; add = {"name":"may"}; test1.push(add); //添加一个元素 console.log(test1); delete test1[2]; //删除一个元素 console.log(test1);
2. Sorting
1. One-dimensional array
test = ["100","23","325"]; //定义个数组 function sortNumber(a,b) //定义排序方法 { return a - b } test1_sort=test.sort(sortNumber); console.log(test1_sort);
2. Two-dimensional array
test1 = [{"name":"tank","total":"100"},{"name":"zhang","total":"23"},{"name":"hao","total":"325"}]; sort_by = function(field, reverse, primer){ //定义排序方法 var key = primer ? function(x) {return primer(x[field])} : function(x) {return x[field]}; reverse = [-1, 1][+!!reverse]; return function (a, b) { return a = key(a), b = key(b), reverse * ((a > b) - (b > a)); } } test1_sort=test1.sort(sort_by('total', true, parseInt)); //根据total,升序排 console.log(test1_sort); test1_sort=test1.sort(sort_by('name', false, '')); //根据name,倒序排 console.log(test1_sort);
It may not seem like a minor problem, but if you don’t use it for a long time, it will become rusty or forgotten.
Readers who are interested in more json-related content can check out the special topics on this site: "Summary of json operation skills in JavaScript" and "Summary of json data operation skills with jQuery"
I hope this article will be helpful to everyone in JavaScript programming.