David Hellsing
David Hellsing

Reputation: 108482

Reorder objects

What is the best way to order and transform:

{
  '32': 'foo',
  '24': 'bar',
  '36': 'doe'
}

into:

[
  {'24': 'bar'},
  {'32': 'foo'},
  {'36': 'doe'}
]

I need to order them based on key, which is a string in the original object. jQuery’s API is allowed to use.

Upvotes: 0

Views: 1145

Answers (1)

Naftali
Naftali

Reputation: 146302

Try this:

function arrayMe(obj){
    var indexes = [];
    for(index in obj){
        indexes.push(index);
    }
    indexes.sort();
    var return_array = [];
    for(var i = 0; i < indexes.length; i++){
        return_array[i] = {};
        return_array[i][indexes[i]] = obj[indexes[i]];
    }
    return return_array;
}

All you would have to do is:

arrayMe(oldObject);

Fiddle: http://jsfiddle.net/maniator/uBqjt/

Upvotes: 2

Related Questions