Judgment of JS empty object

Use the Object.entries() method

An array of key-value pairs for the given object's own enumerable string-keyed properties (ie: returns an array containing the object's enumerable properties). Each key-value pair is an array with two elements: the first element is the property's key (always a string), and the second element is the property value.

If an empty array is returned, it means that the object does not have any enumerable properties, which in turn means it is empty.

const obj = { name: "Zhang San" };

if (Object.entries(obj).length === 0) // indicates an empty object

Object.entries(obj).length === 0

Example:

const obj = { foo: "bar", baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

// 类数组对象
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]

// 具有随机键排序的类数组对象
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]

// getFoo 是一个不可枚举的属性
const myObj = Object.create(
  {},
  {
    getFoo: {
      value() {
        return this.foo;
      },
    },
  },
);
myObj.foo = "bar";
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]

For more information, please refer to: Object.entries()

Guess you like

Origin blog.csdn.net/AdminGuan/article/details/132586489