0

I guess I didnt really know how to ask this question for me to find an answer.

So I have three variables that are going to make this function do what it has to

    function gatherDataForGeographic(ele) {
        var $this = $(ele)
        var $main_title = $this.find('.options-title'),
            $option = $this.find('.option');
        var arr = []
        var reportAreas = reportManager.getReportAreasObject();


        $option.each(function () {
            var $this = $(this)
            var $checkbox = $this.find('.checkbox');
            var type = $this.data('type'),
                index = $this.data('index');

            if ($checkbox.hasClass('checkbox--checked')) {
                console.log(reportAreas.type)
            } else {
                return true;
            }
        })
        return arr;
    }
    //this will return an object that I need to index  
    var reportAreas = reportManager.getReportAreasObject();

    //this will get the a key that i need from the object 
    var type = $this.data('type');

    //this will give me the index I need to grab
    var index = $this.data('index');

So what I am trying to do is go through the object based on the type(or key) from the option selected by a user

The problem... It is looking for reportArea.type[index] and is not recognizing it as a variable and I keep getting undefined because .type does not exist.

Is there a way for it to see that type is a variable and not a key?

Christian4423
  • 1,746
  • 2
  • 15
  • 25

2 Answers2

1

You can use dynamic properties in JS using the bracket syntax, not the dot syntax:

reportAreas[type]

That will resolve to reportAreas['whateverString'] and is equivalent to reportAreas.whateverString- reportAreas.type however, is a literal check for type property.

Rob M.
  • 35,491
  • 6
  • 51
  • 50
1
reportArea[type][index]

JavaScript objects are just key-value pairs and the dot syntax is just syntactic sugar for the array notation.

object['a']

and

object.a

Are the same thing, basically.

dtanders
  • 1,835
  • 11
  • 13