convert a string containing dots to a property accessor in javascript - Javascript String Operation

Javascript examples for String Operation:String Parse

Description

convert a string containing dots to a property accessor in javascript

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){//  ww w .  j  av  a  2s.c o m
var bar = {
    a: {
        b: {
            c: 'test'
        }
    }
}
var foo = 'a.b.c',
    arr = foo.split('.'),
    o = bar;

arr.forEach(function(key, i) {
    if (i === arr.length-1) {
        o[key] = 'Hello World'
    }else{
        o = o[key];
    }
});
console.log(bar);
    }

      </script> 
   </head> 
   <body>  
   </body>
</html>

Related Tutorials