Computer >> Computer tutorials >  >> Programming >> Javascript

Convert object to array of objects in JavaScript


Suppose, we have an object containing data about some people like this −

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

We are required to write a JavaScript function that takes in one such object. And our function should separate the data regarding each unique person into their own objects.

Therefore, the output for the above object should look like −

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

Example

The code for this will be −

const obj = {
   "Person1_Age": 22,
   "Person1_Height": 170,
   "Person1_Weight": 72,
   "Person2_Age": 27,
   "Person2_Height": 160,
   "Person2_Weight": 56
};
const separateOut = (obj = {}) => {
   const res = [];
   Object.keys(obj).forEach(el => {
      const part = el.split('_');
      const person = part[0];
      const info = part[1].toLowerCase();
      if(!this[person]){
         this[person] = {
            "name": person
         };
         res.push(this[person]);
      }
      this[person][info] = obj[el];
   }, {});
   return res;
};
console.log(separateOut(obj));

Output

And the output in the console will be −

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