Reputation: 79
I have the following object that looks as follows:
{A: 52, B: 33}
And I need to convert it to the following:
["A", 52], ["B", 33]
How would one go by doing this?
Upvotes: 0
Views: 71
Reputation: 135425
The current way to do this is with Object.entries -
const a = {"A": 52, "B": 33}
console.log(Object.entries(a))
// [ [ "A", 52 ], [ "B", 33 ] ]
Here's an older way using Array.prototype.reduce
-
var a = {"A": 52, "B": 33};
var b = Object.keys(a).reduce(function(xs, x) {
return xs.concat([[x, a[x]]]);
}, []);
// => [["A", 52], ["B", 33]]
Upvotes: 1
Reputation: 11869
try this if you are using jquery:
var obj = {'value1': 'prop1', 'value2': 'prop2', 'value3': 'prop3'};
var array=[];
$.map(obj, function(value, index) {
array.push([index, value]);
});
alert(JSON.stringify(array));
var obj = {'value1': 'prop1', 'value2': 'prop2', 'value3': 'prop3'};
var array=[];
$.map(obj, function(value, index) {
array.push([index, value]);
});
alert(JSON.stringify(array));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 3
Reputation: 5927
This is pretty simple, but might required checking for hasOwnProperty and such:
var result = [];
for (key in obj) {
result.push([key, obj[key]]);
}
Upvotes: 6