如何检查对象是否为空?
例如:
private brand:Brand = new Brand();
我试过了:
if(this.brand)
{
console.log('is empty');
}
不工作
使用Object.keys(obj).length
检查它是否为空。
输出:3
资料来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
你可以像这样使用Object.keys
:
class Brand { }
const brand = new Brand();
if (Object.keys(brand).length === 0) {
console.log("No properties")
}
如果要检查对象是否至少有一个非null,非undefined属性:
Object.values()
获取数组中对象的所有值some
检查是否至少有一个值const hasValues =
(obj) => Object.values(obj).some(v => v !== null && typeof v !== "undefined")
class Brand { }
const brand = new Brand();
if (hasValues(brand)) {
console.log("This won't be logged")
}
brand.name = null;
if (hasValues(brand)) {
console.log("Still no")
}
brand.name = "Nike";
if (hasValues(brand)) {
console.log("This object has some non-null, non-undefined properties")
}
您还可以使用lodash检查对象
if(_.isEmpty(this.brand)){
console.log("brand is empty")
}
JSON.stringify(this.brand)==='{}'
Object.keys(myObject).length == 0
可以使用空属性创建Map obj,并且大小可能不起作用。对象可能不等于空或未定义
但是使用上面的代码,您可以找到对象是否真的为空
Object.values(this.brand).some(b => b != null);
好的方法是有一个简短的功能,你可以在你的应用程序的任何地方使用:
export const isEmpty = (obj) => {
return obj === null || undefined
? true
: (() => {
for (const prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true;
})();
};
如果您构建ECMA 7+可以尝试Object.entries(obj).length === 0 && obj.constructor === Object
小心Object.keys
和Array.some
解决方案,万一你的对象甚至没有初始化,值得null
。
还要关心没有关键的undefined
。
const objNotInitialized = null;
console.log(Object.keys(objNotInitialized));
在这种情况下,您可以添加额外的支票,从而产生最终的解决方案:
function isEmpty(obj) {
return !obj || !Object.keys(obj).some(x => obj[x] !== void 0);
}
console.log(isEmpty({
x: void 0,
}));
console.log(isEmpty(null));
console.log(isEmpty({
key: 'value',
}));
如果你可以使用Object.values
:
function isEmpty(obj) {
return !obj || !Object.values(obj).some(x => x !== void 0);
}
console.log(isEmpty({
x: void 0,
}));
console.log(isEmpty(null));
console.log(isEmpty({
key: 'value',
}));
const obj = {};
// Using Object.keys to loop on the object keys and count them up
if (!Object.keys(obj).length) {
console.log('#1 obj is empty');
}
// What if a key worth undefined ?
const objWithUndefinedKey = {
x: void 0,
};
// Using Object.keys is not enough, we have to check the value behind to remove
// undefined values
if (!Object.keys(objWithUndefinedKey).some(x => objWithUndefinedKey[x] !== void 0)) {
console.log('#2 obj is empty');
}
// Or more elegant using Object.values
if (!Object.values(objWithUndefinedKey).some(x => x !== void 0)) {
console.log('#3 obj is empty');
}
// Alternative is to use for ... in
let empty = true;
for (key in objWithUndefinedKey) {
if (objWithUndefinedKey[key] !== void 0) {
empty = false;
}
}
if (empty) {
console.log('#4 obj is empty');
}