480

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?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Hailwood
  • 89,623
  • 107
  • 270
  • 423

3 Answers3

915

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];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true
Doktor J
  • 1,058
  • 1
  • 14
  • 33
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 19
    Maybe this goes without saying, but I think it might be worth explicitly pointing out `prop` must be of type `string` and or resolve to type `string`. – prasanthv Jun 24 '15 at 00:51
  • 1
    IMHO that's quite obvious... – ThiefMaster Jun 24 '15 at 21:33
  • 15
    and what about nested objects? – sarkiroka Nov 25 '16 at 07:21
  • 1
    What happens if the property does not exist? Does it return undefined? – Tigerware Feb 28 '18 at 10:31
  • 2
    @BluE: Wouldn't it have been easier to test? ;) Yes, accessing an *undefined* property returns `undefined`. – ThiefMaster Feb 28 '18 at 14:51
  • 2
    For the answer completeness sake, I believe it's a good idea to add info about non-existing prop and `undefined` to your answer. People asking for this question most likely don't know what will be returned in this case. – Alexander Abakumov Apr 13 '18 at 14:43
  • @sarkiroka this has now been answered :) – Doktor J Mar 11 '19 at 20:35
  • Reading up on this subject and getting my head around this topic - but given bracket notations ability to use STRINGS and VARS - is there any use cases or benefits to using dot notation any more? – Wally Mar 28 '20 at 07:53
  • dot notation is more readable and shorter. you should always use it unless the key contains characters not allowed outside strings (anything but alphanumeric characters and underscores) or variables. – ThiefMaster Mar 28 '20 at 08:00
  • works also for classes, exg.: class A{ wurzel=12; } B = new A; console.log(B['wurzel']); – Nikolai Ehrhardt Aug 15 '21 at 10:56
  • @ThiefMaster what if I want obj to be a string as well? Is there no way to do it without using eval? – savram Oct 28 '21 at 01:14
97

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.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Prusprus
  • 7,987
  • 9
  • 42
  • 57
  • 2
    this will not work if `prop` string will contain array indexes – SET001 Mar 25 '15 at 15:50
  • 3
    Such as this? http://jsfiddle.net/amofb8xa/8/ – Prusprus Mar 25 '15 at 17:52
  • Accessing nested properties can be done much simpler, check out http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable/30974910#30974910 – Mr Br Jun 22 '15 at 08:11
11

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>
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Junco
  • 281
  • 1
  • 4
  • 12