brooksbp
brooksbp

Reputation: 1986

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']
]

Upvotes: 11

Views: 45473

Answers (4)

Aadit M Shah
Aadit M Shah

Reputation: 74204

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.

Upvotes: 18

holographic-principle
holographic-principle

Reputation: 19738

Using lodash.js (or underscore.js)

var obj = {'a': 'aa', 'b': 'bb'};

_.pairs(obj);

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

lodash.js is an aspiring successor to underscore.js, originated as a fork of the original project. In my opinion, a must use for anyone who values their time.

Upvotes: 2

Paul S.
Paul S.

Reputation: 66324

If you have a browser that supports Object.getOwnPropertyNames and Array.prototype.map

var obj = {'a': 'aa', 'b': 'bb'}, arr;
arr = Object.getOwnPropertyNames(obj).map(function(e) {return [e, obj[e]];});
// [["a", "aa"], ["b", "bb"]]

Browser support table here


As Crazy Train points out, if you are only interested in enumerable properties, Object.keys will work too. In this example both would have the same result.

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102753

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)

Upvotes: 24

Related Questions