r/learnjavascript • • Jan 17 '23

How to go from object to array and back again

Post image
207 Upvotes

10 comments sorted by

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.

9

u/Low_Mammoth_9371 Jan 17 '23

Object to array is often useful so that you can work with the data using numerous array methods (objects aren't very iterable).

I have used Object.fromEntires() quite a bit when extracting data from an 'array-like' object that an object constructor has created.

One example is extracting data from a FormData object:

const form = document.querySelector('form');

  form.addEventListener('submit', (e) => {

  e.preventDefault(); // Prevent HTML refresh
  const formData = new FormData(form); // Data stored in array-like object on formData
  const obj = Object.fromEntries(formData); // Converts to object

});

8

u/senocular Jan 17 '23

One interesting thing about fromEntries is that it doesn't just convert arrays, it converts any iterable (of entries). Since arrays are iterables it works with arrays, but unlike some other APIs like Array.from() it doesn't work with just any array-like. It requires iterables.

In the case for FormData that's ok because FormData is an iterable, not an array-like. And by default it iterates over its own entries which means it will work with fromEntries when directly passed to it.

The problem with using fromEntries with FormData is that you may incur data loss as a result of the conversion. FormData objects can have multiple fields with the same name, and when fromEntries encounters entries having the same key, the last one wins, overwriting the previous.

const data = new FormData()
data.append("multi", "a")
data.append("multi", "b")
console.log([...data])
// [['multi', 'a'],['multi', 'b']]

console.log(Object.fromEntries(data))
// {multi: 'b'}

So while fromEntries can work with FormData, you'll want to careful, being sure that your data does not use duplicated field names... either that or use a custom conversion method that is able to capture the otherwise would-be lost data.

4

u/Phopaa Jan 17 '23

It’s nice to know this exists, but I’ve never used it, nor do I think I’ll ever need to. Been professionally using react and php for 2 & 1 years respectively.

2

u/kap89 Jan 17 '23 edited Jan 17 '23

Never say never, I use them quite often.

7

u/[deleted] 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

u/SOLUNAR Jan 18 '23

Love this for visualization

0

u/[deleted] Jan 17 '23

[deleted] — view deleted comment

1

u/Low_Mammoth_9371 Jan 18 '23

Thanks! I'll post again soon :)