最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sorting - Sort javascript keyvalue pairs inside object - Stack Overflow

programmeradmin0浏览0评论

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. 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?

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. 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?

Share Improve this question asked Dec 20, 2013 at 8:16 metal_manmetal_man 6921 gold badge13 silver badges25 bronze badges 5
  • possible duplicate of How may I sort a list alphabetically using jQuery? – CodingIntrigue Commented Dec 20, 2013 at 8:18
  • There is no reason to sort an object. An object's properties are always displayed in alphabetical order. – nderscore Commented Dec 20, 2013 at 8:19
  • this key/value pairs are feed for drop down list. And that list should be sorted by value. I have no idea how to achieve this. – metal_man Commented Dec 20, 2013 at 8:22
  • Array sorting is a valid but yours is a object – Prasath K Commented Dec 20, 2013 at 8:25
  • I know. I thought that it is possible. As I saw on some tutorials, javascript object are not sorted - but mine is. No matter in which order, it sorts array by the key. – metal_man Commented Dec 20, 2013 at 8:50
Add a ment  | 

2 Answers 2

Reset to default 3

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 es 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. 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.

发布评论

评论列表(0)

  1. 暂无评论