Home > Mobile >  Accessing dynamic properties of an Object in React
Accessing dynamic properties of an Object in React

Time:04-14

I’m checking whether there is a placeholder present in the “all” string within alertDetails object so my question is I need to access email,sms,fax property that appears dynamically based on user’s input (the code is a part of an alert box in which an user can choose to send alert via different delivery methods) so I saved all the possible delivery methods in an array and tried like below;

Const delmethod=[“email”,”sms”,”fax”]

for(let i=0;i<delmethod.length;i  )
{
Console.log(alertDetails &&
            alertDetails.alertMessage &&
            alertDetails.alertMessage[${lang}] &&
            alertDetails.alertMessage[${lang}].all
            ? alertDetails.alertMessage[${lang}][‘${delmethod(i)}’].includes('placeholder')
            : false;
   }

P.S:the property “all” is fixed it’s just the email fax will be changing based on user’s input, to sum it up I want to return true if “placeholder” exists in any of the strings(all,email,fax,sms) the method I tried just prints the del method array, I’d appreciate any help thanks!

CodePudding user response:

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