How to check if an object is empty{}

In actual development, it is often necessary to judge whether an object is empty. If it is empty, subsequent operations cannot be performed. The following
methods can be used to judge
1. According to for...in to traverse the object, return true if it exists, otherwise return false

for ( let i in obj) {
    return true;
}
return false

2. Use the JSON.stringify() method that comes with JSON to judge. (It probably means that it is specially for the string '{}', to judge)

if (JSON.stringify(obj) === '{}') {
    return true;
}
return false;

3. Use Object.keys() in ES6 to judge (this method is recommended)
The Object.keys() method will return an array consisting of the enumerable properties of a given object. If our object is empty, then he will return an empty array.

Object.keys(obj).length === 0 ? '空':'不为空'

practical application

spaceObj is an object format as follows

Dangdangdang, business requirement code function realization:

function handleConfirm() {
  let isEmpty = false;
  Object.values(spaceObj).forEach(item => {
    if (Object.keys(item).length === 0) {
      isEmpty = true;
    }
  });
  if (isEmpty) {
    return;
  }
 
  save();
}

 

Guess you like

Origin blog.csdn.net/qq_37485170/article/details/130224717