How to Convert Object to Array of Objects in JavaScript

To convert an Object to Array of Objects in JavaScript, you can use the Object.values()” function. The Object.values() is a built-in function that returns an array of a given object’s own enumerable property values.

Example 1

const person = {
   person1: {
       name: "tarak",
       age: 34,
       professional: "coder"
   },
   person2: {
       name: "nidhi",
       age: 21,
       profession: "student"
   },
   person3: {
       name: "krupa",
       age: 34,
       profession: "businessman"
    }
}

const array = Object.values(person);
console.log(array)

Output

[
   { name: 'tarak', age: 34, professional: 'coder' },
   { name: 'nidhi', age: 21, profession: 'student' },
   { name: 'krupa', age: 34, profession: 'businessman' }
]

In the above example, we have data like person1, person2, and person3, but this isn’t very pleasant since we don’t want to write every time person1, person2, and person3. So, instead of this, we can convert them to arrays and easily get value by iterating them.

Example 2

To convert a complex object into an array of objects in JavaScript, you can use the “Object.keys()” function. The Object.keys() is a built-in method that returns an array of a given object’s own enumerable property names.

const employeeData = {
  'Paresh Sharma': {
    language: "javascript",
    exp: "2+ year",
    jobType: "work from home"
  },
  'Sonu Dangar': {
    language: "Python",
    exp: "intern",
    jobType: "work from office"
 },
 'Nilesh Mayani': {
    language: "Java",
    exp: "5+ year",
    jobType: "work from home"
 },
}
const array = [];
Object.keys(employeeData).forEach((key) => {
     array.push({
     name: key,
     about: employeeData[key]
   })
});

console.log(array);

Output

[
   {
      name: 'Paresh Sharma',
      about: {
        language: 'javascript',
        exp: '2+ year',
        jobType: 'work from home'
   }
   },
   {
       name: 'Sonu Dangar',
       about: { language: 'Python', exp: 'intern', jobType: 'work from office' }
   },
   {
       name: 'Nilesh Mayani',
       about: { language: 'Java', exp: '5+ year', jobType: 'work from home' }
   }
]

In the above example, we can keep object keys in the array. The Object.keys() method is useful if we want to convert an object into an array of objects and the object keys.

That’s it.

Leave a Comment