简体   繁体   中英

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

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