0

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++){
            console.log(processorStock[i].filterType)
            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>';
         $('#update').html(output);

     }

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.

4
Contributors
4
Replies
20
Views
3 Years
Discussion Span
Last Post by Troy III
0

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;
0

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

0

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

0

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

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

Edited by Troy III

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.