는 내가 아래와 같이 객체에 존재하는 모든 부동산/하위 속성에서 실행할 필요가 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);
}
});
}
사람이 일을하는 청소기/덜 수동 방법을 알고있는 경우
, 그것은 감사하겠습니다.
'sanitizeStr'는 무엇을하고 있는가? 기능을 추가하십시오. –
꽤 관련성이 있다고 생각하지 않기 때문에 포함하지 않았습니다. 그냥 문자열을 대체합니다. 나는 기본적으로 수동으로 하나씩 수행하지 않고 모든 속성에서 해당 함수를 실행하는 더 좋은 방법을 찾아 내려고 노력하고 있습니다. – saadq
가능한 중복 개체 속성을 통해 (http://stackoverflow.com/questions/8312459/iterate-through-object-properties) –