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

后端 未结 15 1818
走了就别回头了
走了就别回头了 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 04:44

    Edit: As user @abd995 noted in the comments, using Array.some() is more efficiënt as it stops the loop when the condition is met:

    const isEmpty = !Object.values(object).some(x => (x !== null && x !== ''));
    

    Original: 2017 answer: Check all values with Object.values(). Returns an array with the values which you can check with Array.every() or Array.some()... etc.

    const isEmpty = Object.values(object).every(x => (x === null || x === ''));
    
    • MDN Object.values()
    • MDN Array.every()

提交回复
热议问题