Dynamic access in JavaScript
MT
7 min read

Hi there👋 in this blog post, you'll learn how to access a value inside the object dynamically in JS.
Let's first start by example of showing different background color for user avatar icon.

1. Here i've created a object and hardcoded few color values
const avatarColors = {
'a': '#FF5733',
'b': '#33FF57',
'c': '#3357FF',
// Add more users and colors as needed
};
Assume that my username is coming from an API call
// Here is an example of API
const fetchUser = async() => {
try {
const response = await fetch('https://someurl');
return await response.json();
} catch (error) {
throw error
}}
Now i'll call the API and get the user data
const avatarColors = {
'a': '#FF5733',
'b': '#33FF57',
'c': '#3357FF',
// Add more users and colors as needed
};const data = await fetchUser();
// now i've the user details in the data variable
const userName = data?.name;
// now let's store the user initial in a variable
if (userName) {
// here i'll getting the first letter of there name and converting to lowercase
const initial = userName.slice(0,1).toLowerCase();
// now next step is to access the color
const color = avatarColors[initial]; // 👈 this is dynamic access
// added undefined check
if (color) {
// now assume i've a element in HTML code
const element = document.getElementById("user-avatar");
// I'm setting the element background color
element.style.background = color;
}}
In the above code i've used the avatar color as an example. You can use instead of switch to avoid some boiler-code also
Check this out for reference👇
Thank you, happy coding!