JSFiddle - React, Tailwind, and code Playground

by thewolff

HTML

<form id="foo-bar" >
      <input type="text" name="foo.bar" />
    </form>
    <form id="foo-bar-baz-qux" >
      <input type="text" name="foo.bar" />
      <input type="text" name="foo.baz.qux" />
      <input type="text" name="qux" />
    </form>

JavaScript

const addToObject = (obj,name) => {
let current = obj
		console.log('my name', name)
    const names = name.split('.');
    console.log('my names', names)
    names.forEach((n) => {
      if(current === '') current = {}
      if(!current[n]) {
        current[n] = ''
      }
      current = current[n]
    })
}

const readFormObject = (id) => {
 const obj = {}
 // candidate had trouble figuring out how to grab the ids, so I told him about document.querySelectorAll
  const inputs = document.querySelectorAll(`#${id} input`)
  console.log('my inputs', inputs)
  inputs.forEach((input) => addToObject(obj, input.name))
  console.log('obj', obj)
  return obj;
}

readFormObject('foo-bar-baz-qux')