0

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

};

London804
  • 905
  • 1
  • 17
  • 37

0 Answers0