Hope that this will not be closed, I can't find any suitable questions.
ValueCode so far, missing the lowercase for the first letter:
// Input: { toastDurationValue: 3000, toastPositionValue: 'bottom' }
// Wanted: { duration: 3000, position: 'bottom' }
const options = Object.keys(element.dataset)
.filter(k => k.startsWith(prefix))
.reduce((prev, curr) => ({
...prev,
[curr.slice(prefix.length).replace(/(Value)$/, '')]: element.dataset[curr]
}), {});
Just add
.toLowerCase()
after
.replace(/(Value)$/, '')
Here:
// Input: { toastDurationValue: 3000, toastPositionValue: 'bottom' }
const options = Object.keys(element.dataset)
.filter(k => k.startsWith(prefix))
.reduce((prev, curr) => ({
...prev,
[curr.slice(prefix.length).replace(/(Value)$/, '').toLowerCase()]: element.dataset[curr]
}), {});
console.log(options);
Output:
{ duration: 3000, position: 'bottom' }
May below snippet can contribute to your solution.
const obj = { toastDurationValue: 3000, toastPositionValue: 'bottom' }
const prefix = 'toast';
Object.keys(obj).forEach(key => {
obj[key] = obj[key.substring(0, key.lastIndexOf('Value')).replace(prefix, '').toLowerCase()] = obj[key];
delete obj[key];
})
console.log(obj);
This can be done in one statement, in an elaborate (difficult to read) way using slice(), replace() and toUpperCase(). The original string stays as it is:
let str = 'hellorandomWORDValue';
const prefix = 'hello';
const str2 = str.replace(prefix, "").slice(0,-5)[0].toUpperCase() + str.replace(prefix, "").slice(0,-5).slice(1)
console.log(str);
console.log(str2);
slice(0,5) -> removes the last 5 letter, so basically removes Value suffix.
replace(prefix,"") -> replaces first instances of the variable string prefix. So basically removes the prefix.
[0].toUpperCase() -> takes out the first character and makes it uppercase.
.slice(1) -> takes out rest of the string (from 1st index). Basically, rest of the string after first character.
const options = Object.keys(element.dataset)
.filter(k => k.startsWith(prefix))
.reduce((prev, curr) => ({
...prev,
[curr.replace(prefix, "").slice(0,-5)[0].toUpperCase() + curr.replace(prefix, "").slice(0,-5).slice(1)]: element.dataset[curr]
}), {});