Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

79
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 + ']');
    });
  });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!