Search code examples
javascriptstringsanitization

Sanitizing all string values in a complex object?


I have a sanitizeStr() function that I need to run on EVERY property/subproperty that exists in an object like the one below:

const data = {
  info: 'schools',
  schools: [
    { name: 'Johnson Elementary', type: 'elementary' },
    { name: 'Iselin Middle School', type: 'middle' }
  ],
  bestStudent: {
    name: 'John',
    grade: 'sixth'
  }
};

The issue is that for every single one of these properties, they may or may not exist. Right now, I'm having to do multiple if checks for each property and manually running the function:

// Is there a better way to do this rather than what I have here:

if (data.info) {
  data.info = sanitizeStr(data.info);
}

if (data.bestStudent) {
  if (data.bestStudent.name) {
    data.bestStudent.name = sanitizeStr(data.bestStudent.name);
  }

  if (data.bestStudent.grade) {
    data.bestStudent.grade = sanitizeStr(data.bestStudent.grade);
  }
}

if (data.schools) {
  data.schools.forEach((school, i) => {
    if (school.name) {
      data.schools[i].name = sanitizeStr(school.name);
    }

    if (school.grade) {
      data.schools[i].grade = sanitizeStr(school.grade);
    }
  });
}

If anyone knows of a cleaner/less manual way of doing this, it would be appreciated.


Solution

  • You could use an iterative and recursive approach for objects and call the function for non objects only.

    function sanitizeStr(s) {
        return '#' + s;
    }
    
    function iterAll(object) {
        Object.keys(object).forEach(function (k) {
            if (object[k] && typeof object[k] === 'object') {
                iterAll(object[k]);
                return;
            }
            object[k] = sanitizeStr(object[k]);
        })
    }
    
    var data = { info: 'schools', schools: [{ name: 'Johnson Elementary', type: 'elementary' }, { name: 'Iselin Middle School', type: 'middle' }], bestStudent: { name: 'John', grade: 'sixth' } };
    
    iterAll(data);
    
    console.log(data);
    .as-console-wrapper { max-height: 100% !important; top: 0; }