Javascript 检查打字稿中的特定对象是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44337856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:28:08  来源:igfitidea点击:

Check if specific object is empty in typescript

javascripttypescript

提问by Unfra

How to check if an object is empty?

如何检查对象是否为空?

ex:

前任:

private brand:Brand = new Brand();

I tried:

我试过:

if(this.brand)
{
  console.log('is empty');   
}

not working.

不工作。

回答by DeepSea

Use Object.keys(obj).lengthto check if it is empty.

使用Object.keys(obj).length来检查它是否是空的。

Output: 3

输出:3

Source:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

来源:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

回答by adiga

You can use Object.keyslike this:

你可以这样使用Object.keys

class Brand { }
const brand = new Brand();

if (Object.keys(brand).length === 0) {
  console.log("No properties")
}

If you want to check if the object has at least one non-null, non-undefinedproperty:

如果你想检查对象是否至少有一个非空非未定义的属性:

  • Get all the values of the object in an array using Object.values()
  • Check if at least one of has value using some
  • 使用获取数组中对象的所有值 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")
}

回答by Aravind

You can also use lodashfor checking the object

您还可以使用lodash来检查对象

if(_.isEmpty(this.brand)){
    console.log("brand is empty")
}

回答by Sareesh Krishnan

JSON.stringify(this.brand) === '{}'

回答by Manoj Kalluri

Object.keys(myObject).length == 0

A Map obj can be created with empty properties and size might not work . Object might not be equal to empty or undefined

可以使用空属性创建 Map obj,大小可能不起作用。对象可能不等于空或未定义

But with above code you can find whether an object is really empty or not

但是通过上面的代码你可以发现一个对象是否真的为空

回答by Er.Kaudam

let contacts = {};
if(Object.keys(contacts).length==0){
      console.log("contacts is an Empty Object");
}else{
      console.log("contacts is Not an Empty Object");
}

回答by regnar

Object.values(this.brand).some(b => b != null);

Object.values(this.brand).some(b => b != null);

回答by jmuhire

The good approach is to have a short function that you can use everywhere in your app :

好的方法是有一个简短的函数,你可以在你的应用程序的任何地方使用它:

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;
        })();
};

回答by Narek Tootikian

If you build ECMA 7+ can try Object.entries(obj).length === 0 && obj.constructor === Object

如果你构建 ECMA 7+ 可以试试 Object.entries(obj).length === 0 && obj.constructor === Object

回答by Grégory NEUT

Careful about Object.keysand Array.somesolutions, in case if your object is not even initialized and worth null.

小心Object.keysArray.some解决方案,以防您的对象甚至没有初始化和值得null

Also care that there is no key worthing undefined.

还关心有没有钥匙值得undefined

const objNotInitialized = null;

console.log(Object.keys(objNotInitialized));



You could add an extra check in that case, leading to the final soluce :

在这种情况下,您可以添加额外的检查,导致最终的 soluce :

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',
}));



If you can use Object.values:

如果您可以使用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');
}