How to Convert Object to Array of Objects in JavaScript

Here are three ways to convert an Object to an Array of Objects in JavaScript.

  1. Using the Object.values()
  2. Using the Object.keys()
  3. Using the Object.entries()

Method 1: Using the Object.values() method

The Object.values() method returns an array of a given object’s enumerable property values.

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' }
]

Method 2: Using the Object.keys() method

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 an object’s 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' }
   }
]

Method 3: Using the Object.entries() Method

To convert the enumerable string-keyed properties of an object to an array, you use the “Object.entries()” method.

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.entries(employeeData);

console.log(array);

Output

Using the Object.entries() Method

That’s it.

Leave a Comment