function checkLegalStr(str=''){
return (str !== '' && str !== '-' && str !== 'N/A')
}
function handleObject(obj={}){
for(let key in obj){
if(typeof obj[key] === 'object'){
handleObject(obj[key]);
}else if(Array.isArray(obj[key])){
obj[key] = obj[key].filter(item=>{return checkLegalStr(item);});
}else{
if(!checkLegalStr(obj[key])){
delete obj[key];
}
}
}
}
const obj = {
name: { first: 'Robert', middle: '', last: 'Smith' },
age: 25,
DOB: '-',
hobbies: [ 'running', 'coding', '-' ],
education: { highschool: 'N/A', college: 'Yale' }
};
console.log(obj);
handleObject(obj);
console.log(obj);
为啥这个结果 obj.hobbies 会有一个空值<1 empty item>
以下是前后输出
{
name: { first: 'Robert', middle: '', last: 'Smith' },
age: 25,
DOB: '-',
hobbies: [ 'running', 'coding', '-' ],
education: { highschool: 'N/A', college: 'Yale' }
}
{
name: { first: 'Robert', last: 'Smith' },
age: 25,
hobbies: [ 'running', 'coding', <1 empty item> ],
education: { college: 'Yale' }
}
实在是奇怪,我感觉我好水啊,有知道的大哥吗
1
yimity 2021-05-19 19:41:19 +08:00 1
typeof [] === "object" // true
|
2
ChrisFreeMan OP @yimity 嗷嗷知道了,多谢大哥
|
4
yimity 2021-05-19 20:29:56 +08:00 1
Object.prototype.toString.call({}) === "[object Object]"
Object.prototype.toString.call([]) === "[object Array]" Object.prototype.toString.call(5) === "[object Number]" ... |