Reputation: 99
I have an object named path which is:
var path = { "firstFloor": ["roomA1", "roomA6", "roomA5", "roomA2", "roomA3", "roomA4", "roomA10"],
"secondFloor": ["roomB4", "roomB5", "roomB6"],
"basementFloor": []}
right now I'm selecting the arrays normally (path.firstFloor etc.), but I need to select these pairs in a function with the key as the parameter, so:
function draw(floor) { //later on I will call this function with parameter firstFloor
$(path.floor).each(function(i, val){ //this is where I need to select.
var roomIdPath = path.firstFloor[i]
//console.log(roomIdPath);
var points = d3.select('#'+roomIdPath).attr('points').split(",");
var midX = (Number(points[0]) + Number(points[6])) / 2;
var midY = (Number(points[1]) + Number(points[3])) / 2;
floorArray.push({"x": midX, "y": midY});
});
}
Not sure if I'm being clear, basically, all I need is a way to use function parameter in jQuery selector. Is there anyway to do that?
Upvotes: 2
Views: 200
Reputation: 1
Not sure if I got the question right: You can iterate over the keys of your elements (with the caveats that floors might be an object with additional properties in the prototype):
for(floor in floors){
//do your thing
}
or better with Jquery:
$.each(floors, function(key, value){
//do the thing you were doing in the question
//key is your floor name, value is your array of rooms
});
Upvotes: 0
Reputation: 2438
try bracket notation path[floor]
instead, the parameter will be a value not a variable, and don't forget to use console.log(variable)
occassionally for debugging purposes
Upvotes: 0
Reputation: 9808
if you are sending keys to function you can use the keys to access values mapped against the key in the object path.
Currently you have used path.floor
, this is wrong as it will look for a key named floor inside path object you need to use path[floor]
. you can do something like this:
function draw(floor) { //later on I will call this function with parameter firstFloor
$(path[floor]).each(function(i, val){ //this is where I need to select.
var roomIdPath = path[floor][i];
//console.log(roomIdPath);
var points = d3.select('#'+roomIdPath).attr('points').split(",");
var midX = (Number(points[0]) + Number(points[6])) / 2;
var midY = (Number(points[1]) + Number(points[3])) / 2;
floorArray.push({"x": midX, "y": midY});
});
}
Upvotes: 2