user460114
user460114

Reputation: 1848

javascript - coldfusion - working with a list

This is probably easy for someone.

I am returning a list of campaignIDs (12,45,66) via JSON to a javascript variable

var campaignList = res.DATA.CAMPAIGNS

Now, given a specified campaignID passed in the URL

var campaignId ='<cfoutput>#url.campaignID#</cfoutput>'

I want to check if the returned list contains this campaignID

Any help much appreciated.

Upvotes: 0

Views: 465

Answers (4)

Phil Parsons
Phil Parsons

Reputation: 2887

I don't like Billy's answer to this, variables within the function have been declared in the global scope and it is somewhat over complicated. If you have a list of ids as a string in your js just search for the id you have from user input.

var patt = new RegExp("(^|,)" + campaignId + "(,|$)");
var foundCampaign = campaignList.search(patt) != -1;

Upvotes: 0

bittersweetryan
bittersweetryan

Reputation: 3443

Here's a bit of a "out of the box" solution. You could create a struct for your property id's that you pass into the json searilizer have the key and the value the same. Then you can test the struct for hasOwnProperty. For example:

var campaignIDs = {12 : 12, 45 : 45, 66 : 66};

campaignIDs.hasOwnProperty("12"); //true
campaignIDs.hasOwnProperty("32"); //false

This way if the list is pretty long you wont have to loop through all of the potential properties to find a match. Here's a fiddle to see it in action:

http://jsfiddle.net/bittersweetryan/NeLfk/

Upvotes: 0

Luke Sneeringer
Luke Sneeringer

Reputation: 9428

Since Array.indexOf sadly isn't cross browser, you're looking at something like:

// assume there is no match
var match_found = false;

// iterate over the campaign list looking for a match,
// set "match_found" to true if we find one
for (var i = 0; i < campaignList.length; i += 1) {
    if (parseInt(campaignList[i]) === parseInt(campaignId)) {
        match_found = true;
        break;
    }
}

If you need to do this repeatedly, wrap it in a function

Upvotes: 0

Billy Cravens
Billy Cravens

Reputation: 1663

Plenty of ways to do it, but I like nice data structures, so ...

Split the list on comma, then loop over list, looking for value:

function campaignExists(campaignList,campaignId) {
    aCampaignList = campaignList.split(',');
    for (i=0;i<aCampaignList.length;i++) {
        if (aCampaignList[i]==campaignId)
            return true;
    }
    return false;
}

Upvotes: 3

Related Questions