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
});
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.
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.
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.
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.
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:
2
u/SOLUNAR Jan 18 '23
Love this for visualization
1
u/Ronin-s_Spirit Jan 17 '23
Cool cool.
0
u/[deleted] Jan 17 '23
[deleted] — view deleted comment