Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop through Object and replace values based on Regex in given Array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 + ']');
    });
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading