user2536680
user2536680

Reputation: 79

Format javascript object

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

Answers (3)

Mulan
Mulan

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

Suchit kumar
Suchit kumar

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

Luan Nico
Luan Nico

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

Related Questions