r/learnjavascript • u/Low_Mammoth_9371 • Jan 17 '23
How to go from object to array and back again
207
Upvotes
7
Jan 17 '23
I think it’s important to note that the original object still exists. Object.entries() returns a new array, so you can continue to use the original. However, if you wanted to iterate over the entries and use Array.map() to modify, it is then useful to us Object.fromEntries() to return a new object with the modified data.
1
u/Low_Mammoth_9371 Jan 17 '23
Code to copy:
const user = {
name: 'Peter Parker',
job: '🕸️',
city: 'New York'
}
// Object to array with Object.entries():
const arr = Object.entries(user);
console.log(arr);
// [
// [ "name", "Peter Parker" ],
// [ "job", "🕸️" ],
// [ "city", "New York" ]
// ]
// Back to object with Object.fromEntries():
const obj = Object.fromEntries(arr);
console.log(obj);
// {
// "name": "Peter Parker",
// "job": "🕸️",
// "city": "New York"
// }2
1
0
24
u/ahpathy Jan 17 '23
I’m curious at to where or when this would be useful. Somewhat of a newer dev so this may just be going over my head.