Skip to content
Advertisement

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

What is the most elegant way to turn this:

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

into this:

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

Advertisement

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)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement