0

I am trying to use the content of a variable as the name of an object property 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

pilchard
  • 12,414
  • 5
  • 11
  • 23
Gonzalo
  • 349
  • 2
  • 5
  • 16
  • 3
    `saveData({ [key]: value });` – Nicholas Tower Oct 31 '21 at 22:51
  • Did you mean `saveData({ key, value })`? Or `saveData(key, value)`? – Bergi Oct 31 '21 at 22:57
  • 1
    I believe what you actually need is `for (const val of arr) { saveData(val); }`. Do not call `Object.entries` on an array! – Bergi Oct 31 '21 at 22:58
  • Does this answer your question? [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – pilchard Nov 01 '21 at 01:07

2 Answers2

2

You can use ES6 Computed Property Names:

for (const [key, value] of Object.entries(arr)) {
    // You can use any expression inside []
    saveData({ [key]: value });
  }
Lucas David Ferrero
  • 1,630
  • 14
  • 40
1

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 });.

loumadev
  • 371
  • 3
  • 12