Home > Software design >  Javascript: Using the variable's content as a name
Javascript: Using the variable's content as a name

Time:11-01

I am trying to use the content of a variable as the name of an object that another function has to save but I can't figure out how to implement it.

  function saveData(val) {
    console.log(val); //Here I need to receive the Object in the format of {key Name: value}, but I am getting the name key, as it is not being interpreted.
  }
  const arr = [
    { name: "John", lastname: "Doe" },
    { name: "John2", lastname: "Doe2" }
  ];
  for (const [key, value] of Object.entries(arr)) {
    saveData({ key: value });
  }

I cannot modify saveData, so how can I send {key: value} in a way that key is interpreted and its content is sent?

Here you can find the CodeSandBox example

CodePudding user response:

You can use ES6 Computed Property Names:

for (const [key, value] of Object.entries(arr)) {
    // You can use any expression inside []
    saveData({ [key]: value });
  }

CodePudding user response:

You can use initializer notation for this. It allows you to create "computed properties".

The syntax is {[variable]: value}, so your saveData call would become saveData({ [key]: value });.

  • Related