要创建一个函数来确定对象的属性为空或包含双引号,如下所示
代码##标题##
private ReturlFalseIfObjectPropertiesEmpty(a) {
Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(a).length != 0 : (
function() {
for (const key in a) return (key != undefined) && (key != "");
}) ();
}
我需要验证的数据
const data = [{"employeeContact": {
"personalPhone": "",
"workPhone": "",
"personalEmail": "",
"workEmail": "",
"currentAddress": "",
"permanentAddress": ""
}}
];
答案 0 :(得分:1)
您可以尝试通过以下建议的方法检查对象中的空值或空字符串:
注意:所有这些结果都显示了一个新的对象数组,这些对象的属性没有空值或''
如果您希望获得其他结果,则显示具有空值或''的字段,则可以将以下条件从 value!= 更改为 value = =” 为您提供理想的结果。
样本数据
const data = [{"employeeContact": {
"personalPhone": "",
"workPhone": "",
"personalEmail": "",
"workEmail": "",
"currentAddress": "sample", // Supplied one with a value
"permanentAddress": ""
}}
];
方法1-将ES7 For Loop与Object.entries一起使用
const employeeContract = data[0].employeeContact;
let result = [];
for (const [key, value] of Object.entries(employeeContract)) {
if (value != '') result.push({ [key]: value }); // This will push a new object with its existing key and assign its value if the object is not empty. Ex. { personalPhone: 'sample'}
}
console.log(result); // [ { currentAddress: 'sample' } ]
方法2-使用ES7 Object.entries(简化)进行过滤
const employeeContract = data[0].employeeContact;
const result = Object.entries(employeeContract).filter(([key, value]) => value != '' ? { [key]: value } : null);
console.log(result); // [ { currentAddress: 'sample' } ]
要在Typescript中使用Object.entries,您需要编辑 tsconfig.json
{
"compilerOptions": {
"target": "es2017", // Use es2017 to use all of its features
"module": "commonjs",
"strict": true,
"esModuleInterop": true
}
}
// Or if you are using ES6 and you only want to use the ES7 Object.entries() feature then, just supply values on the "lib" property
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"lib": ["es6", "dom", "es2017.object"] // Add this line to enable using Object.entries()
}
}
希望这会有所帮助