Determining if all attributes on a javascript object are null or an empty string

后端 未结 15 1803
走了就别回头了
走了就别回头了 2020-12-08 04:08

What is the most elegant way to determine if all attributes in a javascript object are either null or the empty string? It should work for an arbitrary number of attributes

15条回答
  •  天命终不由人
    2020-12-08 05:01

    You can use the Array.reduce prototype on your object's keys.

    Assuming that the object is structured as follows:

    var obj = {
        x: null,
        y: "",
        z: 1
    }
    

    you can use the following instruction to discover if all of it's properties are unset or set to empty string using just one line:

    Object.keys(obj).reduce((res, k) => res && !(!!obj[k] || obj[k] === false || !isNaN(parseInt(obj[k]))), true) // returns false
    

    If you want to discover if all of it's properties are set instead you have to remove the negation before the conditions and set the initial result value to true only if the object has keys:

    Object.keys(obj).reduce((res, k) => res && (!!obj[k] || obj[k] === false || !isNaN(parseInt(obj[k]))), Object.keys(obj).length > 0) // returns false as well
    

提交回复
热议问题