⭐️ more front-end technology and knowledge, search subscription number JS bacteria subscription

It is easy to check if an array is empty by calling the length method. How do you check if an object is empty ❓

Null here means that the object has no property of its own

So let’s say I have two objects, one is obj and one is anotherObj

let obj1 = {
    name: 'oli'.child: {
        name: 'oliver'}}let obj2 = {
    [Symbol('name')]: 'alice'
}

let obj3 = Object.defineProperty({}, 'name', {
    value: 'alice'.enumerable: false
})

let obj4 = Object.create(null)

// We need a function that does not have its own attributes

isEmpty(obj1) // false
isEmpty(obj2) // false
isEmpty(obj3) // false
isEmpty(obj4) // true
Copy the code

❗️ thought for a long time to check whether the object has a Symbol property can only use getOwnPropertySymbols method, if there is a better method welcome to leave a message

Method 1: traversal

For in, and check with the hasOwnProperty method to see if there is a key that can’t be iterated into a property enumerable is false

const isEmptyObj = object= > {
    if(!!!!!Object.getOwnPropertySymbols(object).length) {
        return false
    }
    for (const key in object) {
        if (object.hasOwnProperty(key)) {
            return false}}return true
}
Copy the code

Method 2: Keys method

Keys returns its own enumerable property, so it’s also impossible to iterate through an attribute that is false

const isEmptyObj = object= > {
    if(!!!!!Object.getOwnPropertySymbols(object).length) {
        return false
    }
    if (Object.keys(object).length) {
        return false
    }
    return true
}
Copy the code

Method 3: JSON method

Using the JSON Stringify method to convert an object to a string, as opposed to the string ‘{}’, this method also fails to get an untraversable property

const isEmptyObj = object= > {
    if(!!!!!Object.getOwnPropertySymbols(object).length) {
        return false
    }
    return JSON.stringify(object) === '{}'
}
Copy the code

Method 4: getOwnPropertyNames method

It is ok to use the getOwnPropertyNames method of Object to get all property names so that even non-enumerable properties can still be obtained.

const isEmptyObj = object= > {
    if(!!!!!Object.getOwnPropertySymbols(object).length) {
        return false
    }
    if(!!!!!Object.getOwnPropertyNames(object).length) {
        return false
    }
    return true
}
Copy the code

Simplified version:

const isEmptyObj = object= > !Object.getOwnPropertySymbols(object).length && !Object.getOwnPropertyNames(object).length
Copy the code

If there is a better way, please leave a comment

Please pay attention to my subscription number, push technical articles about JS irregularly, only talk about technology not gossip 😊

EOF