JavaScript object: access variable property by nam

2018-12-31 00:06发布

This question already has an answer here:

If I have a javascript object that looks like below

var columns = {
  left: true,
  center : false,
  right : false
}

and I have a function that is passed both the object, and a property name like so

//should return false
var side = read_prop(columns, 'right');

what would the body of read_prop(object, property) look like?

3条回答
低头抚发
2楼-- · 2018-12-31 00:20

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];
}
查看更多
孤独总比滥情好
3楼-- · 2018-12-31 00:28

Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the 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>

查看更多
牵手、夕阳
4楼-- · 2018-12-31 00:35

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.

查看更多
登录 后发表回答