检查typescript中特定对象是否为空

Unf*_*fra 14 javascript typescript

如何检查对象是否为空?

例如:

private brand:Brand = new Brand();
Run Code Online (Sandbox Code Playgroud)

我试过了:

if(this.brand)
{
  console.log('is empty');   
}
Run Code Online (Sandbox Code Playgroud)

不工作

Dee*_*Sea 24

使用Object.keys(obj).length检查,如果它是空的.

输出:3

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


luk*_*s_o 16

这是两个最流行的答案之间的比较,它们的含义确实略有不同:

let o1 = {}
console.log(JSON.stringify(o1) === '{}')
console.log(Object.keys(o1).length === 0)
// true
// true

let o2 = { p: undefined }
console.log(JSON.stringify(o2) === '{}')
console.log(Object.keys(o2).length === 0)
// true
// false

let o3 = { l: null }
console.log(JSON.stringify(o3) === '{}')
console.log(Object.keys(o3).length === 0)
// false
// false
Run Code Online (Sandbox Code Playgroud)


adi*_*iga 10

您可以这样使用Object.keys

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

if (Object.keys(brand).length === 0) {
  console.log("No properties")
}
Run Code Online (Sandbox Code Playgroud)

如果要检查对象是否至少具有一个non-nullun-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")
}
Run Code Online (Sandbox Code Playgroud)


Ara*_*ind 9

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

if(_.isEmpty(this.brand)){
    console.log("brand is empty")
}
Run Code Online (Sandbox Code Playgroud)

  • 为 js 原生功能嵌入 lodash 感觉有点大材小用。 (3认同)
  • @DurkoMatko,使用 lodash 进行深度相等(至少需要几行重新编码)和基本的“为空”检查之间存在很大差异。为相同的基本函数和本机函数嵌入 lodash 与在已经大量使用 lodash 的项目中使用 isEmpty 之间也存在差异。 (2认同)

kaz*_*vac 8

这是我所知道的最快的构造,尽管它使用了一些令人费解的for...in不循环的循环(在我的测试中,它大约比 2 倍快Object.keys

export function isObjectEmpty(object: Record<string, unknown>): boolean {
  for (const property in object) {
    // if any enumerable property is found object is not empty
    return false;
  }

  return true;
}
Run Code Online (Sandbox Code Playgroud)


Er.*_*dam 7

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


Man*_*uri 5

Object.keys(myObject).length == 0
Run Code Online (Sandbox Code Playgroud)

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

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