skip to Main Content

Im trying to have something liek this:

let temp={`${otherName}`: `${otherValue}`}

but I get alot of errors with it.

I expected no errors and I know its a typo but ive searched for a soulision for 1 hour. I tried different quotes.

code:

 const otherName = document.getElementById(`adminPanelManageUserOtherName`).value;
    const otherValue = document.getElementById(`adminPanelManageUserOtherValue`).value;

let temp={`${otherName}`: `${otherValue}`}

2

Answers


  1. You could create temp first and then use template strings to assign values to it:

    let temp = {};
    temp[`${otherName}`] = `${otherVale}`;
    
    Login or Signup to reply.
  2. there are multiple ways to implement what you want. The most basic implementation is by using computed property key

    let temp = { [otherName]: otherValue };
    

    the square brackets syntax allows you to dynamically make a key based on the variable you put inside.

    If for some reasons you need to dynamically add multiple values in an object (since from what you’re doing you’re getting values from an element), then you can probably use this:

    let temp = {};
    // loop or something
    temp[otherName] = otherValue;
    

    this is useful for loops or adding multiple key-value pairs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search