EN
JavaScript - transpose object into key/value array
1
answers
0
points
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
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
References
0 comments
Add comment