最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if all attributes is null or empty string with lodash? - Stack Overflow

programmeradmin2浏览0评论

I have an object:

const obj = {
    name: "",
    age: null
}

How can I check if all attributes is null or "" with lodash ? Is so, return true, if some attributes is not null or "" then false.

I have an object:

const obj = {
    name: "",
    age: null
}

How can I check if all attributes is null or "" with lodash ? Is so, return true, if some attributes is not null or "" then false.

Share Improve this question edited Mar 27, 2020 at 10:58 Ori Drori 194k32 gold badges238 silver badges229 bronze badges asked Mar 27, 2020 at 10:55 user13089222user13089222
Add a ment  | 

2 Answers 2

Reset to default 6

With lodash you can use _.every() to check if all properties are empty:

const obj = {
  name: '',
  age: null
}

const result = _.every(obj, v => v === '' || _.isNull(v))

console.log(result)
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.15/lodash.js"></script>

You could use Object.values, Array.every and Array.includes:

const obj1 = { name: "", age: null }
const obj2 = { name: "", age: null, b: 0 }
const obj3 = { name: "", age: null, b: NaN }
const obj4 = { name: "", age: null, b: false }
const obj5 = { name: "", age: null, b: undefined }

function checkEmptyOrNull(obj) {
  return Object.values(obj).every(v => ['', null].includes(v))
}

console.log(checkEmptyOrNull(obj1))
console.log(checkEmptyOrNull(obj2))
console.log(checkEmptyOrNull(obj3))
console.log(checkEmptyOrNull(obj4))
console.log(checkEmptyOrNull(obj5))

发布评论

评论列表(0)

  1. 暂无评论