0

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?

Suchit kumar
11.9k3 gold badges26 silver badges46 bronze badges
asked May 12, 2015 at 17:48
3
  • To be clear, do you want it to be converted to a string in the provided format? Commented May 12, 2015 at 17:52
  • Do you want an Array of Arrays [["A", 52], ["B", 33]] ? Can you explain why you want to convert to this format? Commented May 12, 2015 at 18:03
  • @talves that's exactly what I need. I need it for use in a highchart. Commented May 12, 2015 at 18:10

3 Answers 3

6

This is pretty simple, but might required checking for hasOwnProperty and such:

var result = [];
for (key in obj) {
 result.push([key, obj[key]]);
}
answered May 12, 2015 at 17:51
Sign up to request clarification or add additional context in comments.

1 Comment

This is certainly the most elegant answer. Since the question wasn't tagged jQuery, a simple 50 byte solution wins over a 83095 byte framework.
3

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>

answered May 12, 2015 at 17:52

1 Comment

Where does this question say jQuery can be used?
1

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]]
answered May 15, 2015 at 8:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.