JavaScript Map

Posted by

In JavaScript, Map is a built-in data structure introduced in ECMAScript 2015 (ES6) that allows you to store key-value pairs. Unlike JavaScript objects, Map allows any type of data to be used as keys, including objects, functions, and primitives. Here’s an overview of how to use Map in JavaScript:

Creating a Map:

You can create an empty Map using the new Map() constructor or initialize it with an array of key-value pairs using the new Map(entries) constructor. Here’s an example:

const map = new Map(); // Empty Map

const entries = [
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
];
const mapWithEntries = new Map(entries);

console.log(map); // Output: Map {}
console.log(mapWithEntries); // Output: Map { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }

Working with Map Entries:

You can add, retrieve, and delete entries in a Map using various methods:

  • set(key, value): Adds a new key-value pair to the Map.
  • get(key): Retrieves the value associated with the specified key.
  • has(key): Checks if a key exists in the Map.
  • delete(key): Removes a key-value pair from the Map.
  • size: Returns the number of key-value pairs in the Map.

Here’s an example :

  const [users, setUsers] = useState([]);

This line declares a state variable called users using the useState hook. The users variable holds an array of user data, and setUsers is a function used to update the value of users. The initial value of users is an empty array [].


<tbody>
                    {users.map((user,index)=>(
                        <tr key={user.id}>
                            <td>{++index}</td>
                            <td>{user.name}</td>
                            <td>{user.email}</td>
                            <td>
                                
                                
                            </td>
                        </tr>
                    ))}
                </tbody>

This section represents the table body (<tbody>) of the table. It uses the map function to iterate over the users array and generate a table row (<tr>) for each user object.

Within the map function, each user is represented by the user variable, and the index is represented by the index variable. The key prop is set to user.id to provide a unique identifier for each table row.

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
1
0
Would love your thoughts, please comment.x
()
x