-1

So, I'm creating a table on which the users will fill out the table's header with their options. For this example let's say I want to create 3 headers as options: "fruits", "desserts" and "others".

The "applicants" will fill their answers for those headers.

The problem I'm trying to solve is the following: I need to sort those answers, and I had the idea to use the header as the variable of the array, and I'd fill that array with the answer, like:

let fruits = [];
fruits.push(*applicant's answers*);

I can create an array with the headers after the table is ready to be filled, like "headers = [fruits, desserts, others]" but I don't know how to create the "fruits = []" or "desserts = []", as I don't know the headers until the table is filled and ready to be answered.

Is there a way to solve this or I'll need to sort it out in an another way?

caulifla
  • 1
  • 2
  • Depends on what “applicants’ answers” look like. Familiarize yourself with [how to access and process nested objects, arrays or JSON](https://stackoverflow.com/q/11922383/4642212) and how to [create objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon Mar 18 '21 at 03:17

1 Answers1

0

You can use an event listener on click of the input entries to run a function with arr.reduce() to iterate over an array of the titles, passing in the inputs values combining both arrays as an object, then push the object into another array with each new entry of your inputs.

const inputs = document.querySelectorAll('.inputs')
const submit = document.getElementById('submit')
const titles = ['fruits', 'deserts', 'others']
let entries = new Array()

const combineArrays = (titles, input) => {
  return titles.reduce((acc, val, index) => {
    acc[val] = input[index].value
    return acc
  }, {})
}

submit.addEventListener('click', () => {
  entries.push(combineArrays(titles, inputs))
  if (entries.length > 0) {
    submit.value = 'Add more'
  }
  console.log(entries)
})
.titles {
display: inline-block;
  width: 5rem;
  line-height: 2em;
}
<div><span class="titles">Fruits : </span><input class="fruits inputs" name="fruits" type="text"></div>
<div><span class="titles">Deserts : </span><input class="deserts inputs" name="deserts" type="text"></div>
<div><span class="titles">Others : </span><input class="others inputs" name="others" type="text"></div>
<span class="titles"></span><input value="Add Entry" type="button" id="submit"></td>
dale landry
  • 7,831
  • 2
  • 16
  • 28