/
deserialize.js
48 lines (39 loc) · 1.06 KB
/
deserialize.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
import { toArray } from 'domassist';
export default function deserialize(data, inputs) {
const index = {};
if (!Array.isArray(inputs)) {
inputs = toArray(inputs);
}
inputs.forEach(input => {
const name = input.getAttribute('name');
let val = data[name];
if (typeof index[name] === 'undefined') {
index[name] = 0;
} else {
index[name] = index[name] + 1;
}
if (Array.isArray(val) && input.tagName !== 'SELECT' && !input.multiple) {
val = val[index[name]];
}
if (typeof val === 'undefined') {
return;
}
if (input.type === 'checkbox' && val === true) {
input.checked = true;
} else if (input.type === 'radio' && input.value === val) {
input.checked = true;
} else if (input.tagName === 'SELECT') {
let v = val;
if (!Array.isArray(val)) {
v = [val];
}
toArray(input.options)
.filter(option => v.indexOf(option.value) > -1)
.forEach(option => {
option.selected = true;
});
} else {
input.value = val;
}
});
}