Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The method to transform an object into an array of objects is to use the Object.entries() method to get an array of key-value pairs, and then use the Array.map() method to transform each pair into an object with properties for the key and value.

Here is an example code snippet:

const obj = { 
  name: 'John', 
  age: 30, 
  occupation: 'Software Developer' 
};

const arrOfObjs = Object.entries(obj).map(([key, value]) => ({ key, value }));

console.log(arrOfObjs);
// Output: 
// [ 
//    { key: 'name', value: 'John' }, 
//    { key: 'age', value: 30 }, 
//    { key: 'occupation', value: 'Software Developer' } 
// ]

Alternatively, you can also use the Object.keys() method to get an array of keys, and then use the Array.map() method to transform each key into an object with properties for the key and the corresponding value from the original object.

Here is an example code snippet:

const obj = { 
  name: 'John', 
  age: 30, 
  occupation: 'Software Developer' 
};

const arrOfObjs = Object.keys(obj).map(key => ({ key, value: obj[key] }));

console.log(arrOfObjs);
// Output: 
// [ 
//    { key: 'name', value: 'John' }, 
//    { key: 'age', value: 30 }, 
//    { key: 'occupation', value: 'Software Developer' } 
// ]