简体   繁体   English

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

[英]Sort array of objects in JavaScript

I got an array of objetcs from PHP via json_encode . 我通过json_encode从PHP获得了objetcs数组。 The problem is that on PHP side items are ordered but when it gets on JS side, items are not in order. 问题在于,在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");

So, how can I order that array by "product" on JavaScript side? 那么,如何在JavaScript端按“产品”排序该数组?

The problem is the fact that what PHP calls "array" can be, but can also not be an array in JavaScript. 问题在于,PHP所谓的“数组”可以是,但也不能是JavaScript中的数组。 You are getting an object (or associative array, or dictionary, or hashtable): 您正在获取一个对象(或关联数组,字典或哈希表):

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

which is not orderable in JavaScript. 在JavaScript中无法排序。 You have three options: convert to a true array (if you don't care about keys, or if you can insert the keys into the objects), use an index array (and sort that instead), or (in ES6) use Map and its contract that it shall preserve the order of items in order of insertion (but it only works on new JavaScript environments). 您有以下三种选择:转换为真数组(如果您不关心键,或者可以将键插入对象),使用索引数组(并对其进行排序),或(在ES6中)使用Map以及它的合同,即应按插入顺序保留项目的顺序(但仅适用于新的JavaScript环境)。

For example, one way would be this (using an index array): 例如,一种方法是这样(使用索引数组):

 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]); }); 
 <!-- results pane console output; see http://meta.stackexchange.com/a/242491 --> <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> 

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

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