I have an object and an array. I try to loop through object keys, check them against a regex in array and then replace the string. What I have so far:
let event = {
"firstKey":"1",
"secondKey": {
"a":"one",
"b":"two",
"c":"three"
},
"id":111934444,
"count":1,
"location":"https://www-domain-org/username=steven&tel=1234",
"title":"lastname=hey",
"sd":"24-bit"
};
let myReg = [
{
name: 'telephone',
reg: /((tel=)|(telephone=))[\d\+\s][^&\/\?]+/gi,
group: '$1'
},
{
name: 'names',
reg: /((username=)|(lastname=))[^&\/\?]+/gi,
group: '$1'
}
];
let secret = function(obj){
Object.values(obj).forEach(function(val) {
myReg.forEach(function(regTest) {
val = val.toString();
val = val.replace(regTest.reg, regTest.group + '[redacted ' + regTest.name + ']');
});
});
return obj;
}
let newEvent = secret(event);
console.log(newEvent);
I do not get the original Object with replaced values. What is wrong with my code? I appreciate any help.
>Solution :
You are setting the local variable val. You should actually use the obj to persist the change.
Try iterating with Object.keys(obj) like this
Object.keys(obj).forEach(function(key) {
myReg.forEach(function(regTest) {
let val = obj[key].toString();
obj[key] = val.replace(regTest.reg, regTest.group + '[redacted ' + regTest.name + ']');
});
});