In this article, we’ll be looking at two ways to quickly convert an array of objects to a Map object in JavaScript.
1. Map() Constructor and Array map()
To convert an array of objects to a map, we can use the Arraymap() method to create an array of key-value pairs, and then pass the resulting array to a Map() constructor to create a Map object.
In the callback passed to the map() method, we return an array containing the key and the value for each object. This will result in an array of key-value pairs:
The Map constructor can take an array of this form as an argument to create a Map object.
2. Map set() and Array forEach()
Another way to convert an array of objects to a map is with the ArrayforEach() method. First, we create a new Map object. Then, we add entries for all the array elements to the Map, by calling the Mapset() method in the callback passed to forEach(). Here’s an example:
You might have seen the double negation operator (!!) used in some JavaScript code. What is its function?
Double negation converts truthy values to the trueBoolean and falsy values to the falseBoolean. It is not a distinct JavaScript operator, but really just a sequence of two negations. Apply the first negation results in false for a truthy value, and true for a falsy value. The second negation will then operate on the normal Boolean value that results.
Note: If you need to convert a value to a Boolean, it’s better to be explicit and use the Boolean constructor instead of double negation. We could have more clearly written the above example as:
Note: We don’t need to convert a value to a Boolean to check if it is truthy or falsy in ternary operators or if statements. We can use the value directly:
if (2) console.log('executed');
if ('') console.log('NOT executed');
if (NaN) console.log('NOT executed');
if ('word') console.log('executed');
if (undefined) console.log('NOT executed');
We can also reverse an array without modifying it by creating a reverse for loop, and in each iteration, adding the array element whose index is the current value of the loop counter to a new array. The new array will contain all the elements reversed at the end of the loop.
Let’s look at some ways to quickly get the length of an object in JavaScript.
1. The Object.keys() Method
To get the length of an object, we can pass the object to the static Objectkeys() method, and access the length property of the resulting array. For example:
Note: Object.keys() only returns the enumerable properties found directly on the object. If you want to include non-enumerable properties in the count, use Object.getOwnPropertyNames() instead:
Note: Object.keys() and Object.getOwnPropertyNames() don’t work for symbolic properties. To count symbolic properties, use Object.getOwnPropertySymbols():
Another method to get the length of an object is to use the JavaScript for...in loop to iterate over the properties of the object and increment a variable in each iteration. The variable will contain the object length after the loop.
const obj = {
color: 'red',
topSpeed: 120,
age: 2,
};
let objectLength = 0;
for (let key in obj) {
if (obj.hasOwnProperty(key)) objectLength++;
}
console.log(objectLength); // 3
Because the for...in loop also iterates over the inherited properties of the object, we use the hasOwnProperty() method to ensure that the property exists directly on the object before incrementing the variable.
In this article, we’ll be learning how to concatenate a bunch of strings in JavaScript with a separator of our choice, like a comma or hyphen.
The Array join() Method
To concatenate strings with a separator, we can create an array containing the strings and call the join() method, passing the separator as an argument. The join() method will return a string containing the array elements joined with the separator. For example:
While this works, it’s better to be explicit by passing the comma as an argument if you need comma separation, as not everyone is aware of the default behaviour.
Note: The join() method will return an empty string if we call it on an empty array. For example:
console.log([].join(',')); // ''
Note: Elements like undefined, null, or empty array values get converted to an empty string during the join:
If we have an array of JavaScript objects that each contain a property of the Date type, for example:
const events = [
{ name: 'Birthday', date: new Date('2022-04-23') },
{ name: 'Shopping', date: new Date('2022-04-17') },
{ name: 'Meeting', date: new Date('2022-04-27') },
];
How can we sort these objects by the date property?
The Array sort() Method
We can easily do this with the Array sort() method:
events.sort((a, b) => a.date.getTime() - b.date.getTime());
The sort method takes a callback function as an argument. It uses the value returned from this function to decide the order in which to sort the values.
If the callback result is negative, a is sorted before b.
If the result is positive, b is sorted before a.
If the result is 0, the sort order of the two values stays the same.
This means that we can just as easily sort the array in descending order like this:
events.sort((a, b) => b.date.getTime() - a.date.getTime());
Now the result will be positive when b is larger than a and this will make sort() place b first.
Note: You can also sort the array by subtracting the Date objects directly:
events.sort((a, b) => b.date - a.date);
While this method also works, it is considerably slower than subtracting with getTime().
Here’s the result of a performance comparison of both methods, each executing for 1 million iterations:
Direct subtraction: 488.675ms
Subtraction with getTime(): 196.909ms
Sorting without Mutating
The sort() method sorts the array in place, which means it gets modified. To prevent this, we can use the slice() method to create a copy of the array for the sort:
const sortedEvents = events.slice().sort((a, b) => a.date - b.date);
Summary: target is the innermost element in the DOM that triggered the event, while currentTarget is the element that the event listener is attached to.
We use the HTML DOM Event object to get more information about an event and carry out certain actions related to it. Events like click, mousedown, and keyup all have different types of Events associated with them. Two key Event properties are target and currentTarget. These properties are somewhat similar and sometimes return the same object, but it’s important that we understand the difference between them so we know which one is better suited for different cases.
An event that occurs on a DOM element bubbles if it is triggered for every single ancestor of the element in the DOM tree up until the root element. When accessing an Event in an event listener, the target property returns the innermost element in the DOM that triggered the event (from which bubbling starts). The currentTarget property, however, will return the element to which the event listener is attached.
Let’s use a simple example to illustrate this. We’ll have three nested div elements that all listen for the click event with the same handler function.
Clicking the div triggered the event which invoke the handler for div3. The click event bubbles, so it was propagated to the two outer divs. As expected, the target stayed the same in all the listeners but currentTarget was different in each listener as they were attached to elements at different levels of the DOM hierarchy.
In camelcase, the first word of the phrase is lowercased, and all the following words are uppercased. In this article, we’ll be looking at some simple ways to convert a JavaScript string to camelcase.
String Regex Replace
We can use the Stringreplace method with regex matching to convert the string to camel case:
The first regular expression matches the first letter with ^\w and the first letter of every word with \b\w. It also matches any capital letter with [A-Z]. It lowercases the letter if it’s the first of the string and uppercases it if otherwise. After that, it removes any whitespace in the resulting word with \s+ in the second regex.
Lodash camelCase Method
We can also use the camelCase method from the lodash library to convert the string to camelcase. It works similarly to our camelize function above.
The static Stringraw() method is so named as we can use it to get the raw string form of template literals in JavaScript. This means that variable substitutions (e.g., ${num}) are processed but escape sequences like \n and \t are not.
For example:
const message = String.raw`\n is for newline and \t is for tab`;
console.log(message); // \n is for newline and \t is for tab
We can use a raw string to avoid the need to use double backslashes for file paths and improve readability.
For example, instead of:
const filePath = 'C:\\Code\\JavaScript\\tests\\index.js';
console.log(`The file path is ${filePath}`); // The file path is C:\Code\JavaScript\tests\index.js
We can write:
const filePath = String.raw`C:\Code\JavaScript\tests\index.js`;
console.log(`The file path is ${filePath}`); // The file path is C:\Code\JavaScript\tests\index.js
We can also use it to write clearer regular expressions that include the backslash character. For example, instead of:
const patternString = 'The (\\w+) is (\\d+)';
const pattern = new RegExp(patternString);
const message = 'The number is 100';
console.log(pattern.exec(message)); // ['The number is 100', 'number', '100']
We can write:
const patternString = String.raw`The (\w+) is (\d+)`;
const pattern = new RegExp(patternString);
const message = 'The number is 100';
console.log(pattern.exec(message)); // ['The number is 100', 'number', '100']
Vuetify provides a wide range of built-in transitions we can apply to various elements to produce smooth animations that improve the user experience. We can use a transition by setting the transition prop on supported components, or wrapping the component in a transition component like v-expand-transition.
Vuetify Expand Transition
To apply the expand transition to an element, we wrap it in a v-expand-transition component. This transition is used in expansion panels and list groups.
Components like v-menu have an origin prop that allows us to specify the point from which a transition should start. For example, we can make the scale transition start from the center point of both the x-axis and y-axis:
A slide x transition makes the element fade in while also sliding in along the x-axis. Unlike a scroll transition, the element slides out in the same direction it slid in from when closed.
Vuetify comes with a built-in transition system that allows us to easily create smooth animations without writing our own CSS. We can scale, fade or translate a UI element with the various transitions available.