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
3 Answers 3
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
Luan Nico
6,0533 gold badges33 silver badges63 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Yogi
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.
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
Suchit kumar
11.9k3 gold badges26 silver badges46 bronze badges
1 Comment
Mulan
Where does this question say jQuery can be used?
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
Mulan
136k35 gold badges240 silver badges276 bronze badges
Comments
lang-js
Arrayof Arrays[["A", 52], ["B", 33]]? Can you explain why you want to convert to this format?