My Technical Notes

Monday, 12 October 2015

Javascript: Setting property using its string name

For this example, check the console log output.


<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

    <script>
        var nestedObject = {
            set: function (obj, propString, value) {
                var propNames = propString.split('.'),
                    propLength = propNames.length - 1,
                    tmpObj = obj;
                for (var i = 0; i <= propLength ; i++) {
                    if (i === propLength) {
                        if (tmpObj[propNames[i]]) {
                            tmpObj[propNames[i]] = value;
                        } else {
                            tmpObj[propNames[i]] = value;
                        }
                    } else {
                        if (tmpObj[propNames[i]]) {
                            tmpObj = tmpObj[propNames[i]];
                        } else {
                            tmpObj = tmpObj[propNames[i]] = {};
                        }
                    }
                }
                return obj;
            },
            get: function (obj, propString) {
                var propNames = propString.split('.'),
                    propLength = propNames.length - 1,
                    tmpObj = obj;
                for (var i = 0; i <= propLength ; i++) {
                    if (tmpObj[propNames[i]]) {
                        tmpObj = tmpObj[propNames[i]];
                    } else {
                        break;
                    }
                }
                return tmpObj;
            }
        };

        Object.prototype.setNested = function(key, value)
        {
            nestedObject.set(this, key, value);
        };

        Object.prototype.getNested = function(key)
        {
            nestedObject.get(this, key);
        };


        var obj = {}
        obj.setNested("a.b", "tahir");
        obj.setNested("a.c", "riyadh");
        obj.setNested("a.d", "shoyeb");
        console.log(obj);
        console.log(obj.a.b);
    </script>
</body>
</html>

No comments: