0

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.

2
  • Those are 2 completely different objects.... one is an object with a few properties and the other is and array with a few object elements... Commented Nov 30, 2011 at 14:52
  • I added "transform" into the first sentence. It’s basically the same data, but I need an array that can be looped in order. Commented Nov 30, 2011 at 14:53

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.