Home > Mobile >  Typescript: check for {}
Typescript: check for {}

Time:07-20

How can I check in TypeScript/JavaScript if an element is {} (here the 1st)?

let lst : any [] = [{}, {name: 'abc'}];

I tried these but none of them worked.

if (lst [0] == {})

if (lst [0].toString () == "{}")

CodePudding user response:

Try Object.keys(obj).length == 0

With your code:

let lst = [{}, {name: 'abc'}];

if (Object.keys(lst[0]).length == 0) {
  console.log("Hey this is empty! length:", Object.keys(lst[0]).length)
  console.log("Other length: ", Object.keys(lst[1]).length)
}

Source: Object.keys

  • Related