JavaScript accessing object properties dynamically

 JavaScript accessing object properties dynamically

At times, you might want to use dynamic access when you are accessing properties of an object.

You can use a function to prefix a string, get a return value and assign it to a variable. Once assigned, you can use it to get access to the values stored in properties.

Check out the example below:

Here, the function is used to prefix "prop" to the string that's passed to the function. All the properties of the object begin with the word prop, thus this works.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic access</title>
</head>
<body>
    <div id="res"></div>
    <script>
        var res = document.getElementById("res");
        function propPrefix(str) {
            return "prop" + str;
        }
        var someObj = {
            propName: "Sam",
            propAge: 25,
            propLocation: "India"
        };
        
        var pname = propPrefix("Name");
        var page = propPrefix("Age");
        var ploc = propPrefix("Location");
        res.innerHTML = (someObj[pname] + " " + someObj[page] + " " + someObj[ploc]);
    </script>
</body>
</html>



Post a Comment

0 Comments

React