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

333
Views
How can I convert a string into a variable without using eval()?

I have a form where I can copy certain sections of the form. The keys output something like this.

question_11_text, question_11_text_copy_0, question_11_text_copy_1, etc ...

I'm trying to put the copied keys in an array so that the output is more organized before being submitted to the endpoint.

question_11_text_copies = [{question_11_text_copy_0: 'text data'}, {question_11_text_copy_1: 'more data'}, etc.]

So far I've been able to write logic that returns question_11_text whenever there is a copy, but I'm trying to set that string value as a name of a variable that is assigned to an array. That way when there are several copies I can check if an array exists with that name, if not create a new array with that name and push the key & value pair to it. Else push the key & value pair. Something like the following

 function makeArray(name) {
  if (variable name exists) {
    // push name to variable
   name.push(name);
  } else {
    // create an array with name and push 
    let name = []
    name.push(name);
  }
};

I've seen other StackOverflow posts on this where the recommendation was to use eval. The problem with eval though it's a very big security risk and so I don't think I can use that in my codebase. How can I convert a string value into a variable name without using eval()?

const onSubmit: SubmitHandler<Inputs> = data => {

function makeArray(name) {
  // How can I convert the parameter 'name' into a variable name?
  if (variable name exists) {
    // push name to variable
   name.push(name);
  } else {
    // create an array with name and push 
    let name = []
    name.push(name);
  }
};

const copies = Object.keys(data).filter(key => key.includes('copy'));
copies.map(copiedQuestion => {
  console.log('remove _copy_n from key', copiedQuestion.slice(0, copiedQuestion.length - 7)); 

  makeArray(copiedQuestion.slice(0, copiedQuestion.length - 7));
});

};

about 4 years ago · Juan Pablo Isaza
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!