Ask Your Question
3

What is the method to transform an object into an array of objects?

asked 2023-05-18 18:59:43 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-18 19:15:02 +0000

qstack gravatar image

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' } 
// ]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-18 18:59:43 +0000

Seen: 8 times

Last updated: May 18 '23