

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ]
- Related Questions & Answers
- Convert object of objects to array in JavaScript
- Convert array of objects to an object of arrays in JavaScript
- Convert an array of objects into plain object in JavaScript
- Converting array of objects to an object of objects in JavaScript
- How to transform object of objects to object of array of objects with JavaScript?
- Convert array of object to array of array in JavaScript
- Converting array of objects to an object in JavaScript
- Convert array of arrays to array of objects grouped together JavaScript
- Convert string with separator to array of objects in JavaScript
- JavaScript Converting array of objects into object of arrays
- Flat a JavaScript array of objects into an object
- JavaScript: Sort Object of Objects
- How to convert array to object in JavaScript
- Sum of array object property values in new array of objects in JavaScript
- Splitting an object into an array of objects in JavaScript
Advertisements