Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a JavaScript object to array

I have this object:

var json = {
  "alex" : [
    {'count' : 1, 'date': 2},
    {'count' : 2, 'date': 2},
  ],
  "alex" : [
    {'count' : 10, 'date': '1'},
    {'count' : 20, 'date': '10'},
  ],
};

How do I convert it to:

var arr = [
  {
    name: 'alex',
    data: [[10,1],[20,2]]
  },
  {
    name: 'bob',
    data: [[10,1],[20,2]]
  }
]
like image 533
Omar Makled Avatar asked May 19 '26 04:05

Omar Makled


1 Answers

var json = {
  "alex" : [
    {'count' : 1, 'date': 2},
    {'count' : 2, 'date': 2},
  ],
  "bob" : [
    {'count' : 10, 'date': '1'},
    {'count' : 20, 'date': '10'},
  ],
};


var res = Object.keys(json).map(function (el) {
  return {
    name: el,
    data: json[el].map(function (e) {
      return [e.count, e.date]    
    })
  }  
})

console.log(res);
like image 127
Oleksandr T. Avatar answered May 20 '26 16:05

Oleksandr T.