清理复杂对象中的所有字符串值?

saa*_*adq 5 javascript string sanitization

我有一个sanitizeStr()函数,需要在对象中存在的每个属性/子属性上运行,如下所示:

const data = {
  info: 'schools',
  schools: [
    { name: 'Johnson Elementary', type: 'elementary' },
    { name: 'Iselin Middle School', type: 'middle' }
  ],
  bestStudent: {
    name: 'John',
    grade: 'sixth'
  }
};
Run Code Online (Sandbox Code Playgroud)

问题是,对于这些属性中的每一个,它们可能存在,也可能不存在。现在,我必须if对每个属性进行多次检查并手动运行该函数:

// 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);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

如果有人知道一种更清洁/更少手动的方法来做到这一点,我们将不胜感激。

Nin*_*olz 8

您可以对对象使用迭代和递归方法,并仅对非对象调用该函数。

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);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)