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

时间:2017-03-27 21:16:49

标签: 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'
  }
};

问题在于,对于这些属性中的每一个,它们可能存在也可能不存在。现在,我必须对每个属性进行多次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);
    }
  });
}

如果有人知道更清洁/更少手动的方式,我们将不胜感激。

1 个答案:

答案 0 :(得分:3)

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



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; }