yash041
yash041

Reputation: 67

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]
] 

Upvotes: 0

Views: 69

Answers (3)

Leonid Pyrlia
Leonid Pyrlia

Reputation: 1702

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);

Upvotes: 1

cmichaelsd
cmichaelsd

Reputation: 23

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

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

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);

Upvotes: 4

Related Questions