frequent
frequent

Reputation: 28523

How to access properties of an object nested within another object in Jquery?

I have been trying this for a while now and can't get it to work.

I'm creating an object:

(function( $, window) { 

    $.widget("mobile.multiview",$.mobile.widget, {

        options: {  
            siteMap: []
            }
        });
 }) (jQuery,this);

And fill it with a string and an event data object like so:

var _mainEventBindings = function () {
    var self = this;

    $(document).on("some-event", function(e, data) {
       self.options.siteMap.push( { type: "external", data: data } );
       });
 }

This works ok. I now have to check the stored event data.toPage property in a loop to see if the string stored there is matching the current string, so I don't add stuff twice.

However I can't get it to work like this:

var j = self.options.siteMap.length;
if (j == 0 ){
    alert("added entry");
    self.options.siteMap.push( { type: "external", data: data } );
    } else {
        for ( i = 0; i <= j; i++) {
            console.log("run "+i);
            console.log( self.options.siteMap);
            console.log( self.options.siteMap[i]);
            if ( data.toPage != self.options.siteMap[i]['data.toPage'] ){
                self.options.siteMap.push( { type: "external", data: data } );
                }
            }
        }

So basically I want to make sure I only have "unique" records in my object. However the above does not work because I cannot seem to access what's stored in the object like I'm doing it. Firebug does not even bother to show an error or a console...

Question:
How can I access the sitemap object's 2nd parameter object's parameters...?

Thanks for help!

Upvotes: 1

Views: 219

Answers (2)

VisioN
VisioN

Reputation: 145468

As it was stated in the comments, you should remove equal sign = from the comparison in your for loop:

for (var i = 0; i < j; i++) {
   ...
}

Since otherwise your loop goes out of bounds.

Upvotes: 1

user235273
user235273

Reputation:

Using self is not a good idea, since it adds to window. Here is an example for what you are trying to achieve.

var s = {},  //create an empty object
    i, siteMap;
s.options = {};
s.options.siteMap = []; //our array

//let's add some data to siteMap array
s.options.siteMap = [{'type': "external0", 'data': 'data0'}, {'type': "external1", 'data': 'data1'}, {'type': "external2", 'data': 'data2'}];

//get the siteMap's properties' property
siteMap = s.options.siteMap;
for (i in siteMap) {
  console.log(siteMap[i].type);  //will print external0, external1 etc.
}

Upvotes: 0

Related Questions