Swastik Yadav

S Y

Navigate back to the homepage

9 useful code snippets for everyday JavaScript development || Part 2

Swastik Yadav
March 10th, 2023 · 1 min read

Hello Everyone

Welcome to this JS code snippets series. Thanks a lot for all the love to the 1st part of this post.

This is the 2nd post with 4 JS code snippets that you can use in your everyday JavaScript development.

Read the first 5 code snippets here.

6. Form data to Object.

{% embed https://youtu.be/la5QYLyjXIU %} This snippet will make your life a lot easier by converting form data into object which you can directly use as payload.

1const formToObject = form =>
2 Array.from(new FormData(form)).reduce(
3 (acc, [key, value]) => ({
4 ...acc,
5 [key]: value
6 }),
7 {}
8 );
9
10formToObject(document.querySelector('#form'));
11// { email: 'test@email.com', name: 'Test Name' }
  • First use the FormData constructor to convert HTML form into FormData.
  • Convert FormData into an Array with Array.from.
  • Use Array.prototype.reduce to achieve the desired object from array.

7. Generate UUID in browser

{% embed https://youtu.be/IgMMdDoazz8 %} Let’s say you need a unique id/key for every item in your list. With this snippet you can generate unique id/key right in your browser.

1const UUIDGeneratorBrowser = () =>
2 ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
3 (
4 c ^
5 (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
6 ).toString(16)
7 );
8
9UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
  • Use Crypto.getRandomValues() to generate a UUID.
  • Use Number.prototype.toString() to convert it to a proper UUID (hexadecimal string).

8. Check if a string is valid JSON.

{% embed https://youtu.be/qWId6SWgkEk %} If you have ever accessed an object from localStorage, you know that you get a stringified version of that object.

And, now you want to check if that stringified object is valid JSON or not.

The below snippet will help you exactly with that.

1const isValidJSON = (str) => {
2 try {
3 JSON.parse(str);
4 return true;
5 } catch (err) {
6 return false;
7 }
8};
9
10// Example
11isValidJSON('{"name":"John","age":30}');
12// true
13isValidJSON('{name:"John",age:30}');
14// false
  • In the try block, we parse the string with JSON Parse method.
  • If string in invalid JSON, catch block will return false else true.

9. Array to CSV

{% embed https://youtu.be/T7Zqff4IwI0 %} You have an array of data, and you want to convert it to CSV, so that you can open it on excel or google sheet.

Well, Vanilla JS can do that also for you.

1const arrayToCSV = (arr, delimiter = ",") =>
2 arr.map((row) => row.map((value) => `"${value}"`).join(delimiter)).join("\n");
3
4// Example
5arrayToCSV([
6 ["one", "two"],
7 ["three", "four"],
8]);
9// '"one","two"\n"three","four"'
  • The Array map method is used to iterate over each level of the array and join each value with a defined delimiter.

So, that is it for this post. If you anyhow liked this post, make sure to show your support.

I also run a weekly newsletter, so you can join me there also.

Thank You!

More articles from Swastik Yadav

9 useful code snippets for everyday JavaScript development || Part 1

In this post we will look at some of the most common JavaScript snippets which will help you with your everyday JavaScript development.

February 15th, 2023 · 2 min read

Understand call, apply, and bind functions in JavaScript like never before.

In this post, we'll take a detailed look at how call, apply, and bind work in JavaScript.

January 20th, 2023 · 1 min read

DiaryOfADev, Success stories of underdog developers.

Every week we share an underdog developer's story and a deep dive into a programming concept.

© 2021–2024 Swastik Yadav
Link to $https://github.com/SwastikyadavLink to $https://www.linkedin.com/in/swastikyadav/