简体   繁体   English

在对象内对javascript键/值对进行排序

[英]Sort javascript key/value pairs inside object

I have some problem with sorting items inside object. 我在对对象内部的项目进行排序时遇到一些问题。 So I have something like this: 所以我有这样的事情:

var someObject = {
    'type1': 'abc',
    'type2': 'gty',
    'type3': 'qwe',
    'type4': 'bbvdd',
    'type5': 'zxczvdf'
};

I want to sort someObject by value, and this is where I have problem. 我想按值对someObject排序,这就是我遇到的问题。 I have sorting function that should return key/value pairs sorted by value: 我有排序功能,应该返回按值排序的键/值对:

function SortObject(passedObject) {
    var values = [];
    var sorted_obj = {};

    for (var key in passedObject) {
        if (passedObject.hasOwnProperty(key)) {
            values.push(passedObject[key]);
        }
    }

    // sort keys
    values.sort();

    // create new object based on Sorted Keys
    jQuery.each(values, function (i, value) {
        var key = GetKey(passedObject, value);
        sorted_obj[key] = value;
    });

    return sorted_obj;
}

and function to get key: 和获取密钥的功能:

function GetKey(someObject, value) {
    for (var key in someObject) {
        if (someObject[key] === value) {
            return key;
        }
    }
}

The problem is in last part when creating new, returning object - it's sorted by key again. 问题出在最后一部分,当创建新的返回对象时-再次按键排序。 Why? 为什么? And this is specific situation when i have to operate on object NOT on array (yes I know that would be easier...) 这是当我必须对对象而不是对数组进行操作时的特定情况(是的,我知道那会更容易...)

Does anyone know how to sort items in object? 有谁知道如何排序对象中的项目?

Plain objects don't have order at all. 普通对象根本没有顺序。 Arrays -that are a special types of objects- have. 数组是一种特殊的对象类型。

The most close thing that you can have is an array with the object values sorted . 您可以拥有的最接近的对象是一个排序了对象值的数组。 Something like, for example: 例如:

 _valuesOfAnObjectSorted = Object.keys(object).map(function(k){ return object[k]; }).sort();

You have two possibilities: 您有两种可能性:

Refactor your object into an array 将对象重构为数组

Something like this: 像这样:

var myObj = [
    ['type1', 'abc'],
    ['type2', 'gty'],
    ...
];

Or even better, since using it somewhere would not rely on array positions but full named keys: 甚至更好,因为在某个地方使用它并不依赖于数组的位置,而是全名键:

var myObj = [
    {name: 'type1', val:'abc'},
    {name: 'type2', val:'gty'},
    ...
];

Use your object with an auxiliar array 将对象与辅助数组一起使用

Wherever you want to use your object ordered by the keys, you can extract the keys as an array, order it and traverse it to access the object 无论您要使用按键排序的对象,都可以将键提取为数组,对其进行排序并遍历以访问该对象

var ordKeys = Object.keys(myObj).sort(); // pass inside a function if you want specific order
var key;
for (var i = 0, len = ordKeys.length; i < len; i +=1) {
    key = ordKeys[i]
    alert(key + " - " + myObj[key]);
}

Combination of both of them 他们两者的结合

If the object is not constructed by you, but comes from somewhere else, you can use the second option approach to construct an array of objects as in the first option. 如果对象不是由您构造的,而是来自其他地方,则可以使用第二种方法来构造对象数组,就像第一种方法一样。 That would let you use your array anywhere with perfect order. 这样一来,您就可以以完美的顺序在任何地方使用阵列。

EDIT 编辑

You might want to check the library underscore.js . 您可能要检查库underscore.js There you have extremely useful methods that could do the trick pretty easily. 那里有非常有用的方法,可以很容易地完成技巧。 Probably the method _.pairs with some mapping would do all the work in one statement. 带有一些映射的方法_.pairs可能会在一条语句中完成所有工作。

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

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