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.

Categories
JavaScript Answers

How to convert JavaScript object with numeric keys into array?

To convert JavaScript object with numeric keys into array, we call the Object.values method.

For instance, we write

const arr = Object.values(obj);

to call Object.values with obj to return an array of property values in the obj object.

Categories
JavaScript Answers

How to merge 2 arrays of JavaScript objects?

To merge 2 arrays of JavaScript objects, we use the spread operator.

For instance, we write

const arr1 = [
  { name: "lang", value: "German" },
  { name: "age", value: "18" },
];
const arr2 = [
  { name: "childs", value: "5" },
  { name: "lang", value: "German" },
];
const arr3 = [...arr1, ...arr2];

to use the spread operator to spread the arr1 and arr2 entries into a new array and assign the array to arr3.