Skip to content
Advertisement

Convert es6 string in dot into an formData key

Given a JS string

let string = 'language.0.name'

how can I convert the string to formData key notation so I can go

'language[0][name]'

I try this but I want short code with regular expression

let temp = '';
_.forEach(key.split(/[.]/), (i, k) => {
   temp += k === 0 ? i : `[${i}]`;
});

Advertisement

Answer

Can do this with a simple split() and reduce()

let strings = ['language.0.name', 'language.0', 'language'];
// parse function
const parseFormStr = (s) => s.split('.').reduce((a, c) => a + `[${c}]`);
// test loop
strings.forEach(s => console.log([s, ' => ', parseFormStr(s)].join('')));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement