List of key value pairs to array of arrays

371
November 26, 2016, at 7:16 PM

have something like the following:

var obj = {1: 2, 3: 4, 5: 6}

Need something like the following:

var ar = [[1, 2], [3, 4], [5, 6]]

I've tried a few things including the following:

var objToAr = $.map(obj, function(key, value) {
    return [key, value];
});
// objToAr = [2, 1, 4, 3, 6, 5]

Using jQuery, what is the most efficient way to accomplish this using jQuery?

Answer 1

Just use Object.keys with Array.prototype.map.

var obj = {1: 2, 3: 4, 5: 6}, 
    arr = Object.keys(obj).map(function (k) { return [+k, obj[k]]; }); 
 
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');

Answer 2
var a = [];
for (i in obj){ a.push([i, obj[i]]); }
Answer 3

try,

var obj = {1: 2, 3: 4, 5: 6};
function conv(obj){
  var rslt = [];
  for (var key in obj) {
   if (obj.hasOwnProperty(key)) {
     rslt.push([key, obj[key]]);
   }      
  }
 return rslt;
}
var ar = conv(obj);
Rent Charter Buses Company
READ ALSO
Uncaught SyntaxError: Unexpected end of input in parseJSON method javascript

Uncaught SyntaxError: Unexpected end of input in parseJSON method javascript

In a webpage that uses javascript, I pass data to a hidden input field using

935
Cannot use &#39;in&#39; operator to search for &#39;length&#39;

Cannot use 'in' operator to search for 'length'

My Website receives the following string from my WCF Service:

480
Show a form at on click and show it with value of a input box

Show a form at on click and show it with value of a input box

I want to show the value of a form on clicking of a checkbox and after selecting a checkbox I want that one of our input box of my form which is disabled show the name of checkbox in that fieldI also want to get the id of that checkbox

250
jQuery Datepicker adding days

jQuery Datepicker adding days

Edit: working fiddle: http://jsfiddlenet/yao6dgex/

408