Bai Chan Kheo Bai Chan Kheo - 4 months ago 8
Javascript Question

Convert object to array of objects in JavaScript

I have some data passed in via a query string and I've converted it to an object like:

{
"Person1_Age": 22,
"Person1_Height": 170,
"Person1_Weight": 72,
"Person2_Age": 27,
"Person2_Height": 160,
"Person2_Weight": 56,
}


I want to convert this to an array of objects like this:

[
{
"name": "Person1",
"age": "22",
"height": 170,
"weight": 72
},
{
"name": "Person2",
"age": "27",
"height": 160,
"weight": 56
}
]


What would be the best way to do this? Thanks!

Answer

You could do this with forEach loop and optional thisArg parameter

var data = {
  "Person1_Age": 22,
  "Person1_Height": 170,
  "Person1_Weight": 72,
  "Person2_Age": 27,
  "Person2_Height": 160,
  "Person2_Weight": 56,
}

var result = [];
Object.keys(data).forEach(function(e) {
  var part = e.split('_');
  var person = part[0];
  var p = part[1].toLowerCase();

  if(!this[person]) {
    this[person] = {name: person}
    result.push(this[person]);
  } 
  
  this[person][p] = data[e];
}, {})

console.log(result);