new to javascript so this is probably a stupid question. I have some code example below.
what i'm trying to do is use the method i've created which takes a filterType and a filter
and then filter by using those two varaibles. The problem i'm having is that I don't know the correct syntax to use a variable as an identifier (think thats the correct term) ? is this possibile?

     function processorFilter(filterType,filter){

         var output = '<ul class = "searchresults">';
         for(var i = 0; i < processorStock.length; i++){
            if(processorStock[i].vendor == filter){
             output += '<ul>';
             output += '<h2>' +processorStock[i].name+ '</h2>';
             output += '<img src="' + processorStock[i].image + '"/img>';
             output += '<p>' + processorStock[i].vendor + '</p>';
             output += '<p>' + processorStock[i].series + '</p>';
             output += '<p>' + processorStock[i].socket + '</p>';
             output += '<p>' + "Stock "+ processorStock[i].stock + '</p>';
             output += '<p>' + '\u00A3' + processorStock[i].price + '</p>';
             output += '</ul>';


         output += '</ul>';


if(processorStock[i].vendor == filter)

where it says .vendor i want to use a variable so if i then decided I wanted to filter by socket type instead of vendor i could just change the value of the variable rather than write an entirely new method

if(processorStock[i].filterType == filter)

so it would look something like the above except thats obviously the wrong syntax.

Recommended Answers

All 4 Replies

Try bracket syntax instead.

processorStock[i]['vendor'] === processorStock[i].vendor;

You can then do really wonky and crazy stuff like....

var myVar = "vendor";

processorStock[i][myVar] === processorStock[i]['vendor'] === processorStock[i].vendor;

ah cheers for that. I ended up fixing it by changing a chunk of my code but its all working now.

feel free to post what you changed or any other info that may help someone else with a simliar problem.

output += '<img src="' + processorStock[i].image + '"/img>';

this one is wrong.
will produce: <img src="imagelocation"/img> a malformed img tag.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.