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

时间:2015-10-01 20:57:33

标签: javascript

[
{
    "_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"
  }
]

如何根据价格对使用post方法创建的以下JavaScript对象数组进行排序?

1 个答案:

答案 0 :(得分:1)

首先使用JSON.parse将json字符串加载到对象中。接下来,一旦将对象加载到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