I'm trying to change a lot of strings and haven't found a "good" way. What I want to do is remove some strings based on different criteria. Exactly:
- change 'PD-111 S/A' to 'PD-111' < remove all instances of 'S/A' when the string starts with 'PD-'
- change 'KL.OTHERSTUFF' to 'KLOTHERSTUFF' < remove all instances of '.' when the string starts with 'KL'
- change 'BD5000-50' to 'BD5000' < remove all instances of '-50' when the string starts with 'BD'
I've tried the .startsWith() and .replace() without any luck and diff iterators like .map to try to create a function to delete based on criteria.
I ended doing a forEach but it's incredibly resource intensive (since the total changes would be around 4k strings). It works but it's really bad I think eventhough I'm a pretty serious noob.
I'll do reproducible code next:
let firstArr = [{
sku: 'PD-123-A S/A',
stock: '0'
},
{
sku: 'PD-123-B S/A',
stock: '1'
},
{
sku: 'PD-123-C S/A',
stock: '1'
}
]
let repl = {
'PD-123-A S/A': 'PD-123-A',
'PD-123-B S/A': 'PD-123-B',
'PD-123-C S/A': 'PD-123-C',
}
firstArr.forEach(element => {
let keys = Object.keys(repl);
let values = Object.values(repl);
for (let i = 0; i < keys.length; i++) {
if (keys[i] === element.sku) {
element.sku = values[i];
}
}
});
console.log(firstArr);