简体   繁体   中英

How do I access data in this javascript MAP object?

I'm making an AJAX call which returns XML data, and this is my 'success:' function (callback):

success: function (data) { 
        var $rowArray = $(data).find("[nodeName=z:row]");
          $rowArray.each(function(index) { // for each date put it into calMap.
          calMap[$(this)[index].title] = $(this).attr("ows_Title");
          calMap[$(this)[index].date]  = $(this).attr("ows_EventDate");
          });
         }   

calMap is a global javascript object declared outside of the function.

var calMap = {};

What I want to do is create a function where I can pass in a title , have it search calMap for that title, and if found, the specific object is returned and I'll be able to access the date property for that object.

Problem is, I can't seem to access the data I insert into the calMap object. For starters, I just want to print the map. Tried eval 'ing it, tried alerting calMap[0] , tried alerting calMap[0].title , but nothing. Can someone help me with this? Thanks!

Update: I want to do something like this:

var data = getData("myTitle");

function getData(title) {
// if title is in calMap, something like this?
var result = (calMap[title])); 
return result;  // returns an object or NOTHING
}

then i'll check if date is defined or not, and if it is, i'll access its properties (ie. data.date . That make sense?

ANSWER: I ended up using an array. STILL think I should be able to use the object MAP, but needed to get my project done.

Here's the final code for the code that accesses the array items:

function hasCalDate(code)
{
    var matched = "";
    for (var f=0;f<calMap.length;f++){
        var re = new RegExp(code);
        if (re.test(calMap[f].title))
        {
        matched = calMap[f].title+','+calMap[f].date;
        }
    }
return matched;
};

Thanks everyone.

Your problem is that the success function is only run when your AJAX request completes. If you want to access calMap safely, you need to do so inside your callback.

You need to initialize calMap as an array (ie square brackets, not curly ones):

var calMap = [];

Then, inside your each function, I'm guessing you want something more like

calMap.push({
    title: $(this).attr("ows_Title"),
    date: $(this).attr("ows_EventDate")
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM