-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathformToObj.js
50 lines (38 loc) · 842 Bytes
/
formToObj.js
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
48
49
50
/*
Give Html Form:
<form id="foo-bar-baz-qux">
<input type="text" name="a.b" />
<input type="text" name="a.c.d" />
<input type="text" name="e" />
</form>
The function should return the following result in javascript console:
{
"a": {
"b": "",
"c": {
"d": ""
}
},
"e": ""
}
Make a function which would take “id” as an argument of a form and return the result like above.
*/
function formToObj(id, obj = {}) {
let form = docuemnt.getElementById(id);
[...form.children].forEach(child => {
let names = child.name.split('.');
let key = obj;
names.forEach((item, index) => {
if (key[item] === undefined) {
if (names.length - 1 === index) {
key[item] = "";
} else {
key[item] = {};
}
}
key = key[item];
})
console.log(obj)
});
}
formToObj(`foo-bar-baz-qux`);