Given a JS string
JavaScript
x
2
1
let string = 'language.0.name'
2
how can I convert the string to formData key notation so I can go
JavaScript
1
2
1
'language[0][name]'
2
I try this but I want short code with regular expression
JavaScript
1
5
1
let temp = '';
2
_.forEach(key.split(/[.]/), (i, k) => {
3
temp += k === 0 ? i : `[${i}]`;
4
});
5
Advertisement
Answer
Can do this with a simple split()
and reduce()
JavaScript
1
5
1
let strings = ['language.0.name', 'language.0', 'language'];
2
// parse function
3
const parseFormStr = (s) => s.split('.').reduce((a, c) => a + `[${c}]`);
4
// test loop
5
strings.forEach(s => console.log([s, ' => ', parseFormStr(s)].join('')));