我有一个对象
const currentData: CreateProjectData = {
title: '',
description: '',
projectType: '',
projectStart: undefined,
projectTime: 0,
};
有没有一种方法可以检查对象中的所有值是否都是伪造的(例如0,undefined,''等),而无需将对象转换为数组然后循环遍历?
答案 0 :(得分:2)
用于for ... in循环迭代对象并检查真实值
const currentData = {
title: '',
description: '',
projectType: '',
projectStart: undefined,
projectTime: 0,
};
var checkFalsyObject = (data) => {
for (var prop in data) {
if (data[prop]) return false;
}
return true;
}
console.log(checkFalsyObject(currentData));
但是更简单的方法是使用Object.values
获取所有值,然后使用Array.prototype.every
检查所传递的回调是否满足所有元素的要求。
const currentData = {
title: '',
description: '',
projectType: '',
projectStart: undefined,
projectTime: 0,
};
const areAllFalsy = Object.values(currentData).every(el=>!el);
console.log(areAllFalsy)
答案 1 :(得分:0)
如果您不想为此创建额外的数组:
function isDubiousData(data) {
for (let p in data)
if (data[p]) return false;
return true;
}
const currentData = {
title: '',
description: '',
projectType: '',
projectStart: undefined,
projectTime: 0,
budget: null,
onTime: false,
bankAccountBalance: 0n,
teamCoherency: NaN,
qualityIndex: -0
};
console.log(isDubiousData(currentData));
currentData.title = "0";
console.log(isDubiousData(currentData));
答案 2 :(得分:0)
由于您需要检查所有对象值,因此除非您要对每个可能的属性进行硬编码,否则任何解决方案 都将涉及某种循环。如果要在不构造任何数组的情况下执行此操作,则唯一的方法是使用for..in
:
let allFalsey = true;
const currentData = {
title: '',
description: '',
projectType: '',
projectStart: undefined,
projectTime: 0,
};
for (const prop in currentData) {
if (currentData[prop]) {
allFalsey = false;
break;
}
}
console.log(allFalsey);
但是使用数组确实要容易得多,使用for..in
确实很愚蠢:
const currentData = {
title: '',
description: '',
projectType: '',
projectStart: undefined,
projectTime: 0,
};
const allFalsey = !Object.values(currentData).some(Boolean);
console.log(allFalsey);
答案 3 :(得分:0)
检查一下
const CreateProjectData = {
title: '',
description: null,
projectType: 1,
projectStart: undefined,
projectTime: 0,
};
for(var key in CreateProjectData){
if(!CreateProjectData[key])
console.log(`${key} is false`);
else
console.log(`${key} is true`);
}