简体   繁体   中英

Convert object key-value pairs to a series of arrays in Javascript

I am new to Javascript. I have a Javascript object like so:

s = {"Toothless":"Dragon","Foo":"Bar"};

I need to convert it into a series of arrays, like so:

out = [["Toothless","Dragon"],["Foo","Bar"]];

This is the reverse of what is discussed in Convert JavaScript array of 2 element arrays into object key value pairs . A JQuery solution is acceptable.

You can map over the items to achieve this:

  s = {"Toothless":"Dragon","Foo":"Bar"}; var out = Object.keys(s).map(function(data){ return [data,s[data]]; }); console.log(out); 

let s = {"Toothless":"Dragon","Foo":"Bar"};

let out = Object.entries(s);

and you get out as an array of small arrays, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

var s = {"Toothless":"Dragon","Foo":"Bar"};
var out = [];
for (var key in s){
    out.push([key, s[key]]);
}

Try this using jQuery.

 var tempArr = []; s = {"Toothless":"Dragon","Foo":"Bar"}; $.each(s,function(i,v){ tempArr.push([i,v]); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM