Categories
JavaScript Answers

How to transform object to array with JavaScript Lodash?

To transform object to array with JavaScript Lodash, we call the values method.

For instance, we write

const arr = _.values(obj);

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

Categories
JavaScript Answers

How to zip two arrays in JavaScript?

To zip two arrays in JavaScript, we use the map method.

For instance, we write

const a = [1, 2, 3];
const b = ["a", "b", "c"];

const c = a.map((e, i) => {
  return [e, b[i]];
});

console.log(c);

to call a.map with a callback that returns an array with arrays of items in a and the items in b at the same position as the item in a.

Categories
JavaScript Answers

How to find and remove objects in an array based on a key value in JavaScript?

To find and remove objects in an array based on a key value in JavaScript, we can use the filter method.

For instance, we write

myArray = myArray.filter((obj) => {
  return obj.id !== id;
});

to call myArray.filter with a callback that returns an array with the objects with id property that doesn’t equal id.

And then we assign the returned array back to myArray to update it.

Categories
JavaScript Answers

How to use optional chaining with arrays and functions with JavaScript?

To use optional chaining with arrays and functions with JavaScript, we use the ?. operator.

For instance, we write

const item = myArray.filter((x) => x.testKey === myTestKey)?.[0];

to call filter to return an array with items in myArray where the testKey property equals myTestKey.

And we get the first item with the optional chaining operator with ?.[0].

Categories
JavaScript Answers

How to use JavaScript foreach loop on an associative array object?

To use JavaScript foreach loop on an associative array object, we use the Object.entries method.

For instance, we write

const h = {
  a: 1,
  b: 2,
};

Object.entries(h).forEach(([key, value]) => console.log(value));

to call Object.entries with h to return a key-value pair array.

Then we call forEach with a callback that destructures the key and value from the array.

And we log the property value of each entry.