Reputation: 1986
What is the most elegant way to turn this:
{
'a': 'aa',
'b': 'bb'
}
into this:
[
['a', 'aa'],
['b', 'bb']
]
Upvotes: 11
Views: 45473
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
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
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
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