Categories
JavaScript Answers

How to convert Map to array of object with JavaScript?

To convert Map to array of object with JavaScript, we use the spread operator and map.

For instance, we write

const myMap = new Map().set("a", 1).set("b", 2);
const arr = [...myMap].map(([name, value]) => ({ name, value }));
console.log(arr);

to create a map with the Map constructor.

Then we call set to add some key-value pairs.

Next, we spread myMap into an array of key-value pair arrays.

And then we call map to get the name and value and put them in an object.

Categories
JavaScript Answers

How to use JavaScript lodash push to an array only if value doesn’t exist?

To use JavaScript lodash push to an array only if value doesn’t exist, we use sets.

For instance, we write

const s = new Set();

s.add("hello");
s.add("world");
s.add("hello");

to create a set with the Set constructor.

And then we call add to add 'hello' and 'world'.

'hello' won’t be added a 2nd time since it already exists.

Categories
JavaScript Answers

How to move item in array to last position with JavaScript?

To move item in array to last position with JavaScript, we use the splice method.

For instance, we write

const a = [1, 2, 5, 4, 3];
a.splice(4, 0, a.splice(2, 1)[0]);
console.log(a);

to remove the 3rd element from the array and return it in an array with a.splice(2, 1).

We get the removed item with index 0.

And then we put it after index 4 by calling splice again with 4, 0, and a.splice(2, 1)[0].

Categories
JavaScript Answers

How to delete property from spread operator with JavaScript?

To delete property from spread operator with JavaScript, we use the rest syntax.

For instance, we write

const myObject = {
  a: 1,
  b: 2,
  c: 3,
};
const { b, ...noB } = myObject;
console.log(noB);

to use the rest syntax to get all the properties except b from myObject.

b is destructured earlier, so it’ll be omitted from noB.

Categories
JavaScript Answers

How to create an associative array in JavaScript literal notation?

To create an associative array in JavaScript literal notation, we can create a map.

For instance, we write

const arr = new Map([
  ["key1", "User"],
  ["key2", "Guest"],
  ["key3", "Admin"],
]);

const res = arr.get("key2");
console.log(res);

to create an associative array with the Map constructor.

Then we call get with the key to get the value associated with the key.