Search code examples
javascripttypescriptoperatorsand-operator

Javascript - how to get the key value in if condition using AND (&&) operator


Is that possible to get the data like that

my sample code for the multiple And Or condition

var dataset =  { "dataone": "dataonevalue", "datatwo": "datatwovalue", "datathree:"" }
switch (dataset.dataone && dataset.datatwo && dataset.datathree) {
      case "":
      case null:
      case undefined:
        console.log("data missing")
        break;
      default:
        dataset.dataone = "dataonevalue"
        dataset.datatwo = "datatwovalue"
        dataset.datathree = "datathreevalue"
    }

I have to show which key has the "" or null or undefined and I have to get the particular key in which any of the three is found in Json object

for example like this

console.log("data missing in datathree")

How to do that ?... Can anyone please help me to solve this ?


Solution

  • I have to show which key has the "" or null or undefined and I have to get the particular key in which any of the three is found in Json object

    Try this:

    let dataset = {
      "dataone": "dataonevalue",
      "datatwo": "",
      "datathree": null
    };
    
    
    for (const item in dataset) {
      let value = dataset[item];
      if (value === "") {
        console.log(`"${item}" is empty`);
      } else if (value === null) {
        console.log(`"${item}" is null`);
      } else if (value === undefined) {
        console.log(`"${item}" is undefined`);
      }
    }

    Hopefully this will help you!