有没有一种方法可以捕获尚未在类中设置的所有字段?我正在解析json文件,有时字段名称会更改,我想知道 尚未设置哪些字段使其更易于修复。以下是我用来设置类中字段的代码示例。这只是一个小样本,我的课程有250多个字段,因此无法一一检查。
const myLand = new mls.Land();
myLand.landLease = trimString(data["LAND LEASE?"]);
myLand.commonInterest = trimString(data["COMMON INTEREST"]);
myLand.landLeaseAmount = trimString(data["LAND LEASE AMOUNT"]);
myLand.landLeaseAmtFreq = trimString(data["LAND LEASE AMT FREQ"]);
myLand.landLeasePurch = trimString(data["LAND LEASE PURCH?"]);
myLand.landLeaseRenew = trimString(data["LAND LEASE RENEW"]);
newListing.land = myLand;
这是Trim函数
function trimString(inputStr: string) {
return (inputStr !== undefined && typeof inputStr === "string") ? inputStr.trim() : undefined;
}
答案 0 :(得分:2)
使用filter
的{{3}},value
和map
的{{1}}。
key
答案 1 :(得分:1)
如果您需要检查代表类的对象的keys
的设置为undefined
,则可以使用Object.keys()和Array.filter(),如下所示:
function trimString(inputStr)
{
return (inputStr !== undefined && typeof inputStr === "string") ? inputStr.trim() : undefined;
}
const myLand = {};
myLand.landLease = trimString("123");
myLand.commonInterest = trimString(" common interest ");
myLand.landLeaseAmount = trimString(null);
myLand.landLeaseAmtFreq = trimString({});
let undefinedKeys = Object.keys(myLand).filter(k => myLand[k] === undefined);
console.log("Undefined fields:", undefinedKeys);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 2 :(得分:0)
您可以只创建一个 expected 字段数组,然后过滤这些字段:
const expectedFields = ["LAND LEASE?", "COMMON INTEREST", "LAND LEASE AMOUNT", "LAND LEASE AMT FREQ", "LAND LEASE PURCH?", "LAND LEASE RENEW"];
const absentFields = expectedFields.filter(field => !(field in data));
如果您还想捕获非字符串类型的字段:
const absentFields = expectedFields.filter(field => typeof data[field] !== "string");
您分配数据的例程也可以放在循环中:
const camelCase = field => field.match(/\w+/g).map((word, i) => (i ? word[0] : "") + word.slice(+!!i).toLowerCase()).join``;
const expectedFields = ["LAND LEASE?", "COMMON INTEREST", "LAND LEASE AMOUNT", "LAND LEASE AMT FREQ", "LAND LEASE PURCH?", "LAND LEASE RENEW"];
// Sample data
const data = { "LAND LEASE?": "a", "LAND LEASE AMOUNT": "n" }
const myLand = {};
for (const field of expectedFields) {
const value = data[field];
if (typeof value === "string") myLand[camelCase(field)] = value.trim();
}
console.log(myLand);
console.log("missing:", expectedFields.filter(field => typeof data[field] !== "string"));