简体   繁体   中英

Iterating through an array inside a conditional && statement in javaScript?

I have an array:

console.log(tenantArray)
(8) ["WeWork", "Regus", "Spaces", "Knotel", "RocketSpace", "HQ Global Workspaces", "Other", "Select All"]

I also have a large data object, which I want to filter using d3, using a checkbox. The filter will be based on two conditions, the "Agency_Bro" property, and whether or not the "Tenant" property matches any of the strings in the tenantArray listed above. In this sense, the "tenantArray" array above is just a dummy used for string matching purposes. Both conditions have to be true for filter.

The filter works fine if it just reads:

d3.selectAll("#JLLCheckbox").on("change", function() {

            var type = "JLL"            
            display = this.checked ? "inline" : "none";
            d3.selectAll(".features")
            .filter(function(d) { 
                return d.properties.Agency_Bro === type             
            })
            .attr("display", display);
});

However, when I try to add in both conditional statements, the checkbox stops working (no data filtered) yet no error message occurs.

d3.selectAll("#JLLCheckbox").on("change", function() {

    var type = "JLL"            
    display = this.checked ? "inline" : "none";

    d3.selectAll(".features")
        .filter(function(d) { 
            return d.properties.Agency_Bro === type &&
                    tenantArray.forEach(function(entry) {
                    if (d.properties.Tenant === entry){
                        return d.properties.Tenant
                    }
                    });         
        })
});

Two questions: any reason the above logic is failing? And, is there a more efficient way to do this, without going through the trouble of the array? Thanks in advance!

Change to this, you can use indexOf() on your array to see if the value is contained inside and if not return false:

return d.properties.Agency_Bro === type &&
   tenantArray.indexOf(d.properties.Tenant) > -1; //Does a boolean check if indexOf() 
   //returns a value greater than -1, which means the value was found in your array
});

Documentation of indexOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

You'd better replace forEach with some method to receive a true/false value:

d3.selectAll("#JLLCheckbox").on("change", function() {

  var type = "JLL"
  display = this.checked ? "inline" : "none";

  d3.selectAll(".features")
    .filter(function(d) {
      return d.properties.Agency_Bro === type &&
        tenantArray.some(function(entry) {
          return d.properties.Tenant === entry;
        });
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM