json排序的方法有哪些

json排序的方法有哪些

技术问答

  1. 使用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);
  1. 使用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);
  1. 使用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);

本文地址:https://www.sztg.com.cn/article/50824.html

如非特殊说明,本站内容均来自于网友自主分享,如有任何问题均请联系我们进行处理!

猜您喜欢