Tips: Iterating Object in Javascript

Zainal Hasan |

As a backend engineer that working with PHP, I am really confused about iterating data that interpreted as an object in Javascript.

Case study

In Laravel, error response on ajax request will be interpreted as an object. And sometimes, we need to show the error message in each field instead of showing on one alert. I used this script to solve it. Let me show the example with dummy data.

Example of old method
Example of old method
Another example of old method
Another example of old method

I must use errors[key] just to get the value. Can you see that this script looks so messed?

Solution

Then, after trying to read Object Reference Page, I found that Object.entries can be restructured using array extras (in the last example section).

Hmm, what do you think about my solution? I think this more simple and readable instead of another method. Am I wrong? give me your opinion on what the best method.

Caveat

Then, be careful using this Object.entries , because of this not compatible with Internet Explorer as mentioned here. Hmm, who cares and using IE in 2020, right? But, if you are truly drive-in IE, just use this polyfill.

Please, like and share if you think this information be helpful. Thank you.

References

Related post