简体   繁体   中英

JSON to object array format

I want to display like convert JSON data to array objects how can solve this problem using jquery or js? JSON data :

[{
  "new": 122,
  "old": 3389,
  "boarding": 1,
  "aws": 10,
  "azure": 12,
  "cli": 41
}];

To array object:

[
  ["new", 122],
  ["old", 3389],
  ["boarding", 1]
]

one more pattern I need it I have an array like this in Ruby

 [37, 
  3, 
  261, 
  1, 
  0, 
  1457]

to convert into add as key entry static

[
["new",37],
["old",3],
["boarding",1]
["aws",0]
["azure",1457]
] 

Firstly note that you do not need jQuery at all for this. jQuery is primarily a tool for amending the DOM. To work with data structures like this native JS is all you need.

To achieve what you require, you can use Object.keys() to get the keys of the 0th object in your original array, then you can loop over them using map() to build a new 2 dimensional array from that data:

 var originalArr = [{ "new": 122, "old": 3389, "boarding": 1, "aws": 10, "azure": 12, "cli": 41 }]; var newArr = Object.keys(originalArr[0]).map(function(key) { return [key, originalArr[0][key]]; }); console.log(newArr); 

Its simple enough. Just enter the array into Object.entries(). like this Object.entries(originalArr[0])

A simple one-line alternative:

const data = [{
  "new": 122,
  "old": 3389,
  "boarding": 1,
  "aws": 10,
  "azure": 12,
  "cli": 41
}];

const result = Object.keys(data[0]).map(k => ([k, data[0][k]]));

console.log(result);

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