ganesh kaspate
ganesh kaspate

Reputation: 2685

Use lodash function to determine if one of the element in object fails

I have an array of object which looks like ,

const test = [{"id": "1", "status": "progress"},{"id": "1", "status": "book"},{"id": "1", "status": "completed"}, {"id": "1", "status": "done"}]

Here I want to get a that if any of the object from the given array has value other than "progress" and "book" it should return false, or else should return true.

I used the following way

const issome = _.some(test, item => !_.includes(["progress", "book"], item.status))

How to implement this ?

thanks.

Upvotes: 0

Views: 397

Answers (3)

user9757842
user9757842

Reputation:

What about this?

_.every(test, item => item.status === "book" || item.status === "progress"))

const test = [{"id": "1", "status": "book"},{"id": "1", "status": "book"},{"id": "1", "status": "book"}, {"id": "1", "status": "book"}]

console.log(_.every(test, item => item.status === "book" || item.status === "progress"));

const test1 = [{"id": "1", "status": "xxxxx"},{"id": "1", "status": "book"},{"id": "1", "status": "book"}, {"id": "1", "status": "book"}]

console.log(_.every(test1, item => item.status === "book" || item.status === "progress"));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 1

dulebov.artem
dulebov.artem

Reputation: 733

if any of the object from the given array has value other than "progress" and "book" it should return false, or else should return true

const test = [{"id": "1", "status": "progress"},{"id": "1", "status": "book"},{"id": "1", "status": "completed"}, {"id": "1", "status": "done"}]
const issome = _.every(test, item => _.includes(["progress", "book"], item.status))

//issome===false because there are values with status other than "book" or "progress"


const test = [{"id": "1", "status": "progress"},{"id": "1", "status": "book"}]
const issome = _.every(test, item => _.includes(["progress", "book"], item.status))

//issome===true because there are values with status "book" or "progress" only

Upvotes: 0

Konrad
Konrad

Reputation: 24661

If it's works it's the right way. You have ! in wrong place. What you are doing now is checking if there is some item that has success not equal to process or book. What I would recommend is not using lodash if it's not neccessary. You could use JavaScript native some and includes

const issome = !test.some(item => ['book', 'progress'].includes(item.status))

Upvotes: 0

Related Questions