json排序的方法有哪些

使用JavaScript中的sort()方法对JSON数组进行排序:

let jsonArray = [{ "name": "Alice", "age": 25 }, { "name": "Bob", "age": 30 }, { "name": "Charlie", "age": 20 }];

jsonArray.sort(function(a, b) {
    return a.age - b.age;
});

console.log(jsonArray);

使用Lodash库中的sortBy()方法对JSON数组进行排序:

const _ = require('lodash');

let jsonArray = [{ "name": "Alice", "age": 25 }, { "name": "Bob", "age": 30 }, { "name": "Charlie", "age": 20 }];

let sortedArray = _.sortBy(jsonArray, 'age');

console.log(sortedArray);

使用Array.prototype.sort()方法和JSON.stringify()对JSON数组进行排序:

let jsonArray = [{ "name": "Alice", "age": 25 }, { "name": "Bob", "age": 30 }, { "name": "Charlie", "age": 20 }];

jsonArray.sort(function(a, b) {
    return JSON.stringify(a) > JSON.stringify(b) ? 1 : -1;
});

console.log(jsonArray);
阅读剩余
THE END