简体   繁体   English

如何对 JavaScript 对象数组进行排序?

[英]How to sort an array of JavaScript objects?

[
{
    "_id": "560be5d1b28f247c38a4df98",
    "name": "sara",
    "location": "hjk",
    "price": 2000,
    "rating": 4.2,
    "__v": 0,
    "description":"beautiful"

  },
{
    "_id": "560be5d1b28f247c20a4df98",
    "name": "zara",
    "location": "hjk",
    "price": 1000,
    "rating": 3.2,
    "__v": 0,
    "description":"amazing"
  }
]

How to sort the following array of JavaScript objects created by using post method according to its price?如何根据价格对以下使用 post 方法创建的 JavaScript 对象数组进行排序?

First load your json string into an object using JSON.parse .首先使用JSON.parse将您的 json 字符串加载到一个对象中。 Next, once you have the object loaded into JavaScript, you can use the built-in sort method to loop through the elements of the array as many times as needed to sort them based on some logic which returns either a positive number, negative number, or 0 indicating which element should go in front of which or if they're of equal sorting position.接下来,一旦您将对象加载到 JavaScript 中,您就可以使用内置的sort方法根据需要循环遍历数组的元素,根据某种逻辑对它们进行排序,该逻辑返回正数、负数、或 0 表示哪个元素应该放在哪个元素之前或者它们是否具有相同的排序位置。

var o=[
{
    "_id": "560be5d1b28f247c38a4df98",
    "name": "sara",
    "location": "hjk",
    "price": 2000,
    "rating": 4.2,
    "__v": 0,
    "description":"beautiful"

  },
{
    "_id": "560be5d1b28f247c20a4df98",
    "name": "zara",
    "location": "hjk",
    "price": 1000,
    "rating": 3.2,
    "__v": 0,
    "description":"amazing"
  }
];
var ascending=true;//change to false for descending
o.sort(function(a,b) {
        return (a.price - b.price)*(ascending?1:-1);
});
//variable "o" now contains our sorted object.
var json = JSON.stringify(o);//convert back to a string
//now do something with either the "o" object or "json" string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM