Categories
JavaScript Answers

How to Convert JavaScript FormData to Object to JSON?

We can convert JavaScript form data objects to JSON strings easily with the Object.fromEntries and the JSON.strinnfiyt methods.

Object.fromEntries lets us convert an array of key-value pair arrays to an object.

And JSON.stringify lets us convert an object to a JSON string with the JSON object.

For instance, we can create a form:

<form>  
  Email <input name='email'>  
  Password <input name='password' type='password'>  
  <input type='submit'>  
</form>

Then we can listen to the submit event on the form with JavaScript:

const form = document.querySelector('form')  
form.addEventListener('submit', (e) => {  
  e.preventDefault()  
  const formData = new FormData(e.target)  
  const json = JSON.stringify(Object.fromEntries(formData));  
  console.log(json)  
})

We call addEventListener on the form to listen to the submit event.

In the submit event callback, we call e.preventDefault to prevent the default server-side submit behavior.

Then we create a form data object from the form with the FormData constructor.

e.target has the form element.

Next, we call Object.fromEntries to convert the formData into an object with the keys being the value of the name attribute of each input, and the value being the inputted value of each field.

And finally, we call JSON.stringify to convert the object into a JSON string with the object.

Therefore, json is something like:

{"email":"abc","password":"abc"}

if we typed in 'abc' into each field.

Categories
JavaScript Answers

How to Get a JavaScript String’s Length in Bytes?

We can use the Blob constructor to get the size of a string in bytes.

For instance, we can write:

const {
  size
} = new Blob(["hello"]);
console.log(size)

We create a blob from a string with the Blob constructor.

Then we get the size property of the blob to get the size.

We should see that size is 5 from the console log.

Get a JavaScript String’s Length in Bytes with TextEncoder

We can also use the TextEncoder constructor to get the size of a string in bytes.

For example, we can write:

const size = (new TextEncoder().encode('hello')).length
console.log(size)

We create a new TextEncoder instance and call encode on it with the string we want to get the size from.

And we should get the same result as the previous example.

Categories
JavaScript Answers

How to Get a Number of Random Elements from a JavaScript Array?

To get a number of random elements from a JavaScript array, we can shuffle it then call slice to get the first n elements from the shuffled array.

For instance, we can write:

const n = 5;
const items = [10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17];
const sample = items
  .sort(() => Math.random() - 0.5)
  .slice(0, n);
console.log(sample)

We call sort on items with a callback that returns a number between -0.5 and 0.5 to return an array with the items shuffled around.

Then we call slice with 0 and n to get the first n items in the shuffled array.

Then sample has the first 5 shuffled items from items since we set n to 5.

Categories
JavaScript Answers

How to Convert an Array of Objects into One Object in JavaScript?

We can use the JavaScript array reduce method to combine objects in an array into one object.

For instance, we can write:

const arr = [{
  key: "11",
  value: "1100"
}, {
  key: "22",
  value: "2200"
}];
const object = arr.reduce((obj, item) => ({
  ...obj,
  [item.key]: item.value
}), {});
console.log(object)

We have the arr array which we want to combine into one object.

To do that, we call reduce with a callback that returns an object with obj spread into the returned object.

And we add the item.key property with itemn.value as its value.

Therefore, object is:

{11: "1100", 22: "2200"}

Use the Array.prototype.map and Object.assign Methods

Another way to combine an array of objects into one object is to map each entry into their own object.

Then we can combine them all into one with Object.assign .

For instance, we can write:

const arr = [{
  key: "11",
  value: "1100"
}, {
  key: "22",
  value: "2200"
}];
const mapped = arr.map(item => ({
  [item.key]: item.value
}));
const object = Object.assign({}, ...mapped);
console.log(object)

We call map with a callback that returns an object the key and value of the object.

Then we spread mapped into Object.assign as arguments to add the properties in the mapped objects into the empty object.

Therefore, object has the same value as the previous example.

Categories
JavaScript Answers

How to Compare Only Dates in Moment.js?

We can use the isAfter method to check if one date is after another.

For instance, we can write:

const isAfter = moment('2010-10-20').isAfter('2010-01-01', 'year');  
console.log(isAfter)

We create a moment object with a date string.

Then we call isAfter on it with another date string and the unit to compare.

Therefore isAfter is false since we compare the year only.

There’s also the isSameOrAfter method that takes the same arguments and lets us compare if one date is the same or after a given unit.

So if we have:

const isSameOrAfter = moment('2010-10-20').isSameOrAfter('2010-01-01', 'year');  
console.log(isSameOrAfter)

Then isSameOrAfter is true since both dates have year 2010.

The isBefore method lets us compare is one date is before another given the unit to compare with.

So if we have:

const isBefore = moment('2010-10-20').isBefore('2010-01-01', 'year');  
console.log(isBefore)

Then isBefore is false since they have the same year.

isSame compares if 2 dates have the same unit.

For instance, if we have:

const isSame = moment('2010-10-20').isSame('2010-01-01', 'year');  
console.log(isSame)

Then isSame is true since they both have year 2010.