Categories
JavaScript Answers

How to convert JavaScript array to a string?

To convert JavaScript array to a string, we use the JSON.stringify method.

For instance, we write

const a = ["a", "b", "c"];
const str = JSON.stringify(a);

to call JSON.stringify with a to convert the a array to a JSON string.

Categories
JavaScript Answers

How to convert base64 string to ArrayBuffer with JavaScript?

To convert base64 string to ArrayBuffer with JavaScript, we use the Buffer.from method.

For instance, we write

const myBuffer = Buffer.from(someBase64String, "base64");

to call Buffer.from with the someBase64String base64 string and 'base64' to convert the base 64 string to a buffer.

Categories
JavaScript Answers

How to append array to FormData and send via AJAX with JavaScript?

To append array to FormData and send via AJAX with JavaScript, we create a FormData object.

For instance, we write

const formData = new FormData();
const arr = ["this", "is", "an", "array"];

for (const a of arr) {
  formData.append("arr[]", a);
}

to loop through the arr array items with a for-of loop.

In the loop, we call formData.append with the key and the value to append to the form data object.

Categories
JavaScript Answers

How to update an array of objects with JavaScript Firestore?

To update an array of objects with JavaScript Firestore, we call the set method.

For instance, we write

firebase
  .firestore()
  .collection("proprietary")
  .doc(docID)
  .set(
    { sharedWith: [{ who: "abc@test.com", when: new Date() }] },
    { merge: true }
  );

to get the proprietary collection with collection.

We get the document with docID with doc.

And we call set to set the sharedWith property to an array with the object we want to add.

We set merge to true to append the item to the existing sharedWith property array in the document.

Categories
JavaScript Answers

How to use Lodash to compare jagged arrays?

To use Lodash to compare jagged arrays, we use the isEqual and sort methods.

For instance, we write

const array1 = [
  ["a", "b"],
  ["b", "c"],
];
const array2 = [
  ["b", "c"],
  ["a", "b"],
];
const isEqual = _.isEqual(array1.sort(), array2.sort());

to call sort on each array to return a sorted version of them.

And then we call isEqual with the sorted array to check if they have the same content.