Skip to content
Advertisement

How can I access the name/key of a bool (not its value)?

New to coding and working in JavaScript. I’m sure there’s a simple way to do this but it’s been hard to pinpoint with Google searches.

I’m trying to find a JavaScript function or something of the sort that will find the name of a bool in an array (not the bool’s value) and return it to me. Also, the bools have to be in an array. I can’t make them object keys for my purposes.

Here is a mock example of what I’m trying to do:

JavaScript:

function dinnerPreferences(){
  var isChinese = false;
  var isItalian = true;
  var isIndian = false;
  var isHomemade = true;
  var isTakeout = false;

  var dinnerOptions = [isChinese, isItalian, isIndian, isHomemade, isTakeout];
  console.log("Dinner options values: " + dinnerOptions);

  function getPreferences(){
    var wantedDinnerOptions = [];
    // Gather the true values in new array: wantedDinnerOptions
    for(i = 0; i <=dinnerOptions.length; i++){

      if(dinnerOptions[i]){
        wantedDinnerOptions.push(dinnerOptions[i]);
      }
    }
    // Access bool values:
    console.log("Confirm true values: " + wantedDinnerOptions);
    // Access bool length:
    console.log("True value index length: " + wantedDinnerOptions.length)
    // Access bool NAMES(???):
    console.log("Object.keys() doesn't work. What else can I use?");
  }
  getPreferences();
}
  dinnerPreferences();

Advertisement

Answer

You will have to restructure your dinnerOptions array in someway. I’d suggest to transform it to an array of objects, as shown below. So, dinnerOptions is still an array but the items in them are more useable/meaningful when present in form of objects.

function dinnerPreferences() {
  const dinnerOptions = [
    { type: "Chinese", availability: false },
    { type: "Italian", availability: true },
    { type: "Indian", availability: false },
    { type: "Homemade", availability: true },
    { type: "Takeout", availability: false },
  ];
  console.log(
    "All dinner options values: " + dinnerOptions.map((opt) => opt.type)
  );

  function getPreferences() {
    const wantedDinnerOptions = [];
    for (let i = 0; i < dinnerOptions.length; i++) {
      if (dinnerOptions[i].availability) {
        wantedDinnerOptions.push(dinnerOptions[i].type);
      }
    }
    console.log("Available dinner options: " + wantedDinnerOptions);
  }
  getPreferences();
}

dinnerPreferences();

Also the condition for the for loop was incorrect, i should be strictly less than dinnerOptions.length. And I’d suggest using let and const instead of var.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement