How to use the findIndex() Method In Javascript
The findIndex() method can be used to ensure that duplicate keys are not added to the map, thereby maintaining only unique key-value pairs.
Example:
const objectsArray = [
{ type: "Company", name: "w3wiki" },
{ type: "Cricketer", name: "Virat Kohli" },
{ type: "Cricketer", name: "Virat Kohli" } // Duplicate entry
];
console.log("Array of objects is: ", objectsArray);
const createdMap = new Map();
objectsArray.forEach(obj => {
// Check if the key is already in the map
if (Array.from(createdMap.keys()).findIndex(key => key === obj.type) === -1) {
createdMap.set(obj.type, obj.name);
}
});
console.log("Created Map: ", createdMap);
// Nikunj Sonigara
Output
Array of objects is: [ { type: 'Company', name: 'w3wiki' }, { type: 'Cricketer', name: 'Virat Kohli' }, { type: 'Cricketer', name: 'Virat Kohli' } ] Created Map: Map(2) { 'Company' => '...
How to Convert an Array of Objects to a Map in JavaScript ?
An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs.
Example:
Input Array:
[
{ type: 'Company', name: 'w3wiki' },
{ type: 'Cricketer', name: 'Virat Kohli' },
{ type: 'Cricketer', name: 'Virat Kohli' }
]
Output Map: Map(2)
{
'Company' => 'w3wiki',
'Cricketer' => 'Virat Kohli'
}
The below approaches can be used to convert an array of objects to a map in JavaScript:
Table of Content
- Using the map() method
- Using the reduce() method
- Using the forEach() method
- Using the Object.enteries() method
- Using the for-of loop
- Using the findIndex() Method