JavaScript: How to turn a dictionary into a list of elements?

Tags:



What is the most elegant way to turn this:

{
    'a': 'aa',
    'b': 'bb'
}

into this:

[
    ['a', 'aa'],
    ['b', 'bb']
]

Answer

Just iterate through the keys:

var dict = { 'a': 'aa', 'b': 'bb' };
var arr = [];

for (var key in dict) {
    if (dict.hasOwnProperty(key)) {
        arr.push( [ key, dict[key] ] );
    }
}

Fiddle (updated per @Jack’s comment, only add direct properties)



Source: stackoverflow