Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
Javascript: Using the variable's content as a name

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use ES6 Computed Property Names:

for (const [key, value] of Object.entries(arr)) {
    // You can use any expression inside []
    saveData({ [key]: value });
  }
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!