score:1

Accepted answer

there are multiple issues with your code. you cannot just use ${lang}. you must surround your string with backticks (`) if you want to use template literals.

to access properties of an object you need a a key i.e. a string which you already have so in this case template literals are not required at all.

when you access an array by index you need to use [] not () so use delmethod[i] instead of delmethod(i). additionally make sure an property exists on an javascript object.

const delmethod = ["email", "sms", "fax"];

const alertdetails = {
  alertmessage: {
    en: {
      all: "emailsfsdfsdfsd",
      fax: "placeholder",
      sms: "sdkjföskjfsödkj"
    },
  },
};

const lang = "en";

for (let i = 0; i < delmethod.length; i++) {
  if (
    alertdetails &&
    alertdetails.alertmessage &&
    // use backticks ` when trying to use template literals
    alertdetails.alertmessage[`${lang}`] &&
    // there is actually no need for template literals here
    alertdetails.alertmessage[lang].all &&
    // you need to make sure "sms" or "fax" or "email" key actually exist on the object
    alertdetails.alertmessage[lang][delmethod[i]] &&
    alertdetails.alertmessage[lang][delmethod[i]].includes("placeholder")
  ) {
    console.log(
      `alertdetails.alertmessage[${lang}][${delmethod[i]}] does have a placeholder`
    );
    console.log(true);
  } else {
    console.log(
      `alertdetails.alertmessage[${lang}] does not have property ${delmethod[i]} or does not have a placeholder`
    );
    console.log(false);
  }
}


Related Query

More Query from same tag