How do I tell if a JS object is empty

Empty objects are not null and undefined

If you want to check whether null or undefined, use non-null.

const a = null const b = undefined console.log(! a) // true console.log(! b) // trueCopy the code

Check whether it is {}

An empty object is an object that exists but does not have any properties or methods in it.

Common Solutions

  • Object.keys()

Use the ES6 syntax object.keys () to judge

const a = {
  name: 'a'
}
const b = {}
console.log(Object.keys(a).length === 0) // false
console.log(Object.keys(b).length === 0) // true
Copy the code
  • JSON.stringify()
const a = {
  name: 'a'
}
const b = {}
console.log(JSON.stringify(a) === '{}') // false
console.log(JSON.stringify(b) === '{}') // true
Copy the code
  • Object.getOwnPropertyNames()
const a = {
  name: 'a'
}
const b = {}
console.log(Object.getOwnPropertyNames(a).length === 0) // false
console.log(Object.getOwnPropertyNames(b).length === 0) // true
Copy the code

A special case

Does this still apply when the object’s key is of the Symbol() data type?

const a = { [Symbol()]: 'a' }

console.log(a) // { [Symbol()]: 'a' }
console.log(JSON.stringify(a) === '{}') // true
console.log(Object.keys(a).length === 0) // true
console.log(Object.getOwnPropertyNames(a).length === 0) // true
Copy the code

Each of these returns true, so the result is incorrect. A is not empty.

Then we can consider using another method when Symbol is used as the key

getOwnPropertySymbols

console.log(Object.getOwnPropertySymbols(a).length === 0) // false
Copy the code

Final solution

1. Combine getOwnPropertySymbols and getOwnPropertyNames

const a = { [Symbol()]: 'a' }
const b = { a: 'a' }
const c = {}

console.log(Object.getOwnPropertyNames(a).length === 0 && Object.getOwnPropertySymbols(a).length === 0) // false
console.log(Object.getOwnPropertyNames(b).length === 0 && Object.getOwnPropertySymbols(b).length === 0)  // false
console.log(Object.getOwnPropertyNames(c).length === 0 && Object.getOwnPropertySymbols(c).length === 0)  // true

Copy the code
  1. Reflect.ownKeys()
const a = { [Symbol()]: 'a' } const b = { a: 'a' } const c = {} console.log(Reflect.ownKeys(a).length === 0) // false console.log(Reflect.ownKeys(b).length === 0) //  false console.log(Reflect.ownKeys(c).length === 0) // trueCopy the code