-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdestructureFormInputToObject.js
More file actions
47 lines (40 loc) · 1018 Bytes
/
Copy pathdestructureFormInputToObject.js
File metadata and controls
47 lines (40 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
Given a HTML structure
<form id="parent">
<input type="text" name="foo.bat" />
<input type="text" name="foo.bar.baz" />
<input type="text" name="fizz" />
</form>
Write a function (in JS) that returns an object with values of text inputs in the form id passed to it.
For eg:
getValues("parent") should return object like
{
"foo": {
"bat" : _____, //Actual value of 1st text box
"bar" : {
"baz" : _____ // Value of 2nd text box
}
},
"fizz" : _____ // Value of 3rd text box
}
*/
function getValues(parent) {
const formElem = document.querySelectorAll(`#${parent} input[type="text"]`);
let obj = {};
for (let input of formElem) {
let inputValue = input.value;
let names = input.name.split(".");
let temp = obj;
for (let i = 0; i < names.length; i++) {
if (!temp[names[i]]) {
temp[names[i]] = {};
}
if (i === names.length - 1) {
temp[names[i]] = inputValue;
}
temp = temp[names[i]];
}
}
console.log(obj);
return obj;
}