如何根据对象(而不是数组)的属性执行合并排序

How do I perform a merge sort based on the property of an object (rather than an Array)?

本文关键字:属性 执行 排序 合并 数组 何根 对象      更新时间:2023-09-26

Background

使用 JavaScript,我需要根据大型 JSON 对象的给定属性对该对象进行排序。 我假设合并排序是最快的方法。 如果这不是最快的方法,请告诉我是什么。 网上有无数针对数组进行合并排序的例子,但对象的例子很少。 下面是一个示例对象:

fruitForSale = {
     1: {"type":"orange","UnitPrice":0.20},
     2: {"type":"banana","UnitPrice":0.30},
     3: {"type":"pear","UnitPrice":0.10},
     4: {"type":"apple","UnitPrice":0.50},
     5: {"type":"peach","UnitPrice":0.70}
}

问题

使用合并排序(或更快的算法),我将如何对fruitForSale对象进行排序,以便最终得到按"类型"排序的对象:

   fruitForSale = {
                     4: {"type":"apple","UnitPrice":0.50},
                     2: {"type":"banana","UnitPrice":0.30},
                     1: {"type":"orange","UnitPrice":0.20},
                     5: {"type":"peach","UnitPrice":0.70},
                     3: {"type":"pear","UnitPrice":0.10}                  
                   }

注意:原始keys(1,2,3,4和5)需要分配给各自的对象,因此1键应始终与{"type":"orange","UnitPrice":0.20}匹配,2键应始终与{"type":"banana","UnitPrice":0.30}匹配,依此类推。

谢谢!

您无法对

对象上的键进行排序,但可以保留自己的排序键数组。

var fruitForSale = {
     1: {"type":"orange","UnitPrice":0.20},
     2: {"type":"banana","UnitPrice":0.30},
     3: {"type":"pear","UnitPrice":0.10},
     4: {"type":"apple","UnitPrice":0.50},
     5: {"type":"peach","UnitPrice":0.70}
},
sortedKeys = Object.keys(fruitForSale).sort(function (i,j) {
    return fruitForSale[i]["type"] > fruitForSale[j]["type"];
});

示例:http://jsfiddle.net/X2hFt/(控制台上显示的输出)

Object.keys 并非在所有地方都受支持,但如果需要,您可以轻松填充。请参阅

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys

哦,如果您对排序的底层实现感到好奇,请参阅:

Javascript Array.sort 实现?