Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

What is the most elegant way to turn this:

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

into this:

[
    ['a', 'aa'],
    ['b', 'bb']
]
like image 314
brooksbp Avatar asked Jul 13 '13 00:07

brooksbp


2 Answers

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)

like image 135
McGarnagle Avatar answered Nov 15 '22 08:11

McGarnagle


Most JavaScript engines now support the Object.entries function:

const list = Object.entries({
    a: "aa",
    b: "bb"
});

console.log(list); // [['a', 'aa'], ['b', 'bb']]

For older engines, you can write a polyfill for it as follows:

if (typeof Object.entries !== "function")
    Object.entries = obj => Object.keys(obj).map(key => [key, obj[key]]);

Hope that helps.

like image 32
Aadit M Shah Avatar answered Nov 15 '22 06:11

Aadit M Shah