在JavaScript中对对象数组进行排序

时间:2016-01-20 00:22:17

标签: javascript arrays sorting

我通过json_encode从PHP获得了一系列的objetcs。问题是PHP上的项目是按顺序排序的,但是当它出现在JS端时,项目不按顺序排列。

myArray[96] = array ( "product" => "Drone",
"quant" => "23",
"available" => "true");

myArray[43] = array ( "product" => "Aereo",
"quant" => "2",
"available" => "false");

myArray[55] = array ( "product" => "Geos",
"quant" => "45",
"available" => "true");

myArray[13] = array ( "product" => "Barsad",
"quant" => "3",
"available" => "true");

那么,如何在JavaScript端按“产品”订购该数组呢?

1 个答案:

答案 0 :(得分:3)

问题在于PHP称为“数组”的事实可能是,但也可能不是JavaScript中的数组。您将获得一个对象(或关联数组,字典或哈希表):

{"96":{"product":"Drone","quant":"23","available":"true"},
 "43":{"product":"Aereo","quant":"2","available":"false"},
 "55":{"product":"Geos","quant":"45","available":"true"}...}

在JavaScript中无法订购。您有三个选择:转换为真实数组(如果您不关心键,或者您可以将键插入对象中),请使用索引数组(并对其进行排序),或者(在ES6中)使用{ {1}}及其合同,它应按插入顺序保留项目的顺序(但它只适用于新的JavaScript环境)。

例如,一种方法是这样(使用索引数组):

Map
var data = {"96":{"product":"Drone","quant":"23","available":"true"},
     "43":{"product":"Aereo","quant":"2","available":"false"},
     "55":{"product":"Geos","quant":"45","available":"true"}};
var keys = Object.keys(data);
keys.sort(function(a, b) {
  var pa = data[a].product;
  var pb = data[b].product;
  if (pa === pb) return 0;
  return (pa < pb) ? -1 : 1;
});
keys.forEach(function(key) {
  console.log(key, data[key]);
});