How to have a unique hover description for every element in an array?

Viewed 37

Not sure if my title accurately describes my dilemma but basically, I have a list of names and I want each of them to have a unique description when hovered over with a mouse.

That sounds easy enough, right?

But the problem is, the names are elements in an array.

I can't exactly do < a title="DESCRIPTION" /> ARRAY CODE < /a> because each name inside that array will have the same hover description.

How would I code it so that each name in my array will have a different hover description?

1 Answers

You can use an object to map descriptions to names. Like this:

const names = {
    'Bob': 'me',
    'Joe': 'my friend',
    'Bill': 'a random guy',
}

Then you can loop over the object with a for in creating elements. Like this:

for (const name in names) {
    $('body').append(`<a title="${names[name]}"> ${name} </a>`);
}

Because objects have a time complexity of O(1), this should be faster than using a multidimensional array. However, JS objects are not ordered. If you need the names to be in order, consider using a map. Like this:

const names = new Map();
names.set('Bob', 'me');
names.set('Joe', 'my friend');
names.set('Bill', 'a random guy');

for (const name of names) {
    $('body').append(`<a title="${name[1]}"> ${name[0]} </a>`);
}
Related