Reputation: 3
I'm trying to compare event.feature.getProperty('township') against timeline.townshipname from my timeline array in my if. Checking for one right now with [0] is fine, but I have a whole column I want to check against. What's the best way to do this?
//Load Timelines
var timeline = [];
jQuery.getJSON(timelines, function(data) {
var entry = data.feed.entry;
jQuery(entry).each(function(){
var townshipname = this.gsx$township.$t;
var timelinename = this.gsx$timeline.$t;
var combined = {townshipname, timelinename};
timeline.push(combined);
});
});
// Output from timeline looks like
// 0: {townshipname: "West Quincy", timelinename: "Ready for drops"}
// 1: {townshipname: "Woodgate", timelinename: "Ready"}
//Add infowindow to identify townships
township_layer.addListener('click', function(event) {
if (event.feature.getProperty('township') == timeline[0].townshipname){
var timepush = timeline[0].timelinename
} else {
var timepush = 'No Timeline Entered'
}
Upvotes: 0
Views: 72
Reputation: 66123
You can create an array of township names from the timeline
array of objects, so that you can compare if a specific township is found in your timeline.
This can be done by:
Array.prototype.map()
to iterate through your timeline
array of objects and return a list of all townshipname
Array.prototype.indexOf()
Example code is as follow:
// Generate an array of townships extract from timeline
var townships = timeline.map(function(item) {
return item.townshipname;
});
// Attempt to search a given township in your generated array
var townshipIndex = townships.indexOf(event.feature.getProperty('township'));
if (townshipIndex !== -1) {
var timepush = timeline[townshipIndex].timelinename;
} else {
var timepush = 'No Timeline Entered';
}
Alternatively, you can use a for...of
loop and break out of it once a match is found. We assume that no timeline is entered as the "ground state", and then we can update that once a match is found:
var timepush = 'No Timeline Entered';
for (var item of timeline) {
if (item.townshipname === event.feature.getProperty('township')) {
timepush = item.timelinename;
break;
}
}
If you really need IE support, then we can use the classic for
loop:
var timepush = 'No Timeline Entered';
for (var i = 0; i < timeline.length; i++) {
if (timeline[i].townshipname === event.feature.getProperty('township')) {
timepush = timeline[i].timelinename;
break;
}
}
Upvotes: 1
Reputation: 1839
So there are a couple of different ways you could this, if you have an indexed array of objects the fastest way would be:
for(var i = 0; i < timeline.length; i++){
if(event.feature.getProperty('township') == timeline[i].townshipname){
var timepush = timeline[i].timelinename;
}
}
I can come up with another example shortly.
Upvotes: 0