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

4
  • 3
    saveData({ [key]: value }); Commented Oct 31, 2021 at 22:51
  • Did you mean saveData({ key, value })? Or saveData(key, value)? Commented Oct 31, 2021 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! Commented Oct 31, 2021 at 22:58
  • Does this answer your question? Add a property to a JavaScript object using a variable as the name? Commented Nov 1, 2021 at 1:07

2 Answers 2

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 });
  }
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

OP already does use object initialiser notation :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.