What is the most elegant way to turn this:
{
'a': 'aa',
'b': 'bb'
}
into this:
[
['a', 'aa'],
['b', 'bb']
]
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With