Languages

JavaScript - transpose object into key/value array

0 points
Asked by:
elmer
646

How can I transpose given object into an array of key/value pairs (objects)?

My object:

var user = { id: 1, name: 'Tom', email: 'tom@email.com' };

Expected result:

[
  { key: 'id', value: 1 },
  { key: 'name', value: 'Tom' },
  { key: 'email', value: 'tom@email.com' }
]
1 answer
0 points
Answered by:
elmer
646

You can combine Object.entries() with map() method to get the intended result.

What you want to do is convert object into array of objects, so the solution for your problem would be:

// ONLINE-RUNNER:browser;

var user = { id: 1, name: 'Tom', email: 'tom@email.com' };

var result = Object.entries(user).map(([key, value]) => ({ key, value }));

console.log(JSON.stringify(result, null, 4));

However, the topic says "key/value array", so here's a second solution:

// ONLINE-RUNNER:browser;

var user = { id: 1, name: 'Tom', email: 'tom@email.com' };

var result = Object.entries(user).map(([key, value]) => [key, value]);

console.log(JSON.stringify(result));

 

See also

  1. JavaScript - convert object to array of key-value pairs

References

  1. Object.entries() - JavaScript | MDN
  2. Array.prototype.map() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join