We could use map
operator of Array here to transform each item. To transform Chosen
and password
fields, we could use Regex and replace
method of string.
const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const myText = "{subjectsChosen:Python,java,Angular}";
myText.replace(re, '$1'); // Python,java,Angular
Below is the full implementation that transform each item.
const items = [
{
"subjectID": 1,
"Chosen" : "{subjectsChosen:Python,java,Angular}",
"password": "{studentpw:123456abcd}"
},
{
"subjectID": 2,
"Chosen" : "{subjectsChosen:SQL,Rprogram,React}",
"password": "{studentpw:987654zyxwv}"
}
];
const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const passwordRegex = new RegExp(/\{studentpw:(.+)\}/, 'i')
const transformedItems = items.map(item => {
return {
...item,
"Chosen": item.Chosen.replace(chosenRegex, '$1'),
"password": item.password.replace(passwordRegex, '$1')
}
});
console.log(transformedItems);
We could also literally use a single regex if we don't want to differentiate them.
const transformRegex = new RegExp(/\{(.+):(.+)\}/, 'i');
....
return {
...item,
"Chosen": item.Chosen.replace(transformRegex, '$2'), // Since there are two regex groups now, use $2
"password": item.password.replace(transformRegex, '$2')
}