-1

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}`}
Simi
  • 11
  • 3
  • 2
    `let temp = { [otherName]: otherValue };` — there's no need to use template literals when all you want is the value of a variable. – Pointy May 31 '23 at 15:20
  • Or you could also remove the opening { and closing } and the ` in the middle and it will work. Like ``${otherName} : ${otherValue}`` – Craig Stroman May 31 '23 at 15:26
  • Note that the most important point of Pointy's comment is the square brackets; these let you use an expression to define the key in an object literal. – Scott Sauyet May 31 '23 at 15:26
  • @CraigStroman: Is there an escaping problem in your sample? How do you use this to create something equivalent to `const temp = {myName: 'myValue'}` – Scott Sauyet May 31 '23 at 15:29
  • @ScottSauyet Yes your right. That was my bad. – Craig Stroman May 31 '23 at 15:36

2 Answers2

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.

catzilla
  • 1,901
  • 18
  • 31
0

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

let temp = {};
temp[`${otherName}`] = `${otherVale}`;
Mureinik
  • 297,002
  • 52
  • 306
  • 350