JavaScript object: access variable property by name as string

This question already has an answer here:

  • Dynamically access object property using variable 10 answers

  • You don't need a function for it - simply use the bracket notation:

    var side = columns['right'];
    

    This is equal to dot notation, var side = columns.right; , except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

    If you NEED a function for it, here it is:

    function read_prop(obj, prop) {
        return obj[prop];
    }
    

    ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:

    function fetchFromObject(obj, prop) {
    
        if(typeof obj === 'undefined') {
            return false;
        }
    
        var _index = prop.indexOf('.')
        if(_index > -1) {
            return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
        }
    
        return obj[prop];
    }
    

    Where your string reference to a given property ressembles property1.property2

    Code and comments in JsFiddle.


    由于我通过上面的答案帮助了我的项目(我提出了一个重复的问题,并在此处提及),因此在嵌套在var中时,我提交了括号表示法的答案(我的测试代码):

    <html>
    <head>
      <script type="text/javascript">
        function displayFile(whatOption, whatColor) {
          var Test01 = {
            rectangle: {
              red: "RectangleRedFile",
              blue: "RectangleBlueFile"
            },
            square: {
              red: "SquareRedFile",
              blue: "SquareBlueFile"
            }
          };
          var filename = Test01[whatOption][whatColor];
          alert(filename);
        }
      </script>
    </head>
    <body>
      <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>
      <br/>
      <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>
      <br/>
      <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>
    </body>
    </html>
    链接地址: http://www.djcxy.com/p/23646.html

    上一篇: 将PHP对象转换为关联数组

    下一篇: JavaScript对象:按字符串名称访问变量属性