Using some(), every() and Object.values to check values from within an object

davidbell_xyz

David Bell

Posted on October 21, 2020

Using some(), every() and Object.values to check values from within an object

Often you want to check if a value is within an object. Heres a way we can do this with some() every() and Object.values().

Object.values

Object.values is used to create an array from the values in an Object. You pass an object into Object.values and it returns an array of the values.

const stock = {
  meat: 5,
  fruit: 10,
  cheese: 6,
}
const valueArray = Object.values(stock)
// [ 5, 10, 6 ]
Enter fullscreen mode Exit fullscreen mode

some()

some() returns true if one thing passes the test depending on the condition passed in. If not it will return false.

const stock = {
  meat: 5,
  fruit: 10,
  cheese: 6,
}
const enoughStock = Object.values(stock).some(el => el >= 6)
console.log(enoughStock)
// true
Enter fullscreen mode Exit fullscreen mode
const kidsParty = {
  suzy: 29,
  bill: 4,
  tim: 2,
  sally: 5,
  ming: 3,
}
const isAdultPresent = Object.values(kidsParty).some(el => el >= 18)
console.log(isAdultPresent)
// true
Enter fullscreen mode Exit fullscreen mode

every()

every() returns true or false depending on the condition if every thing passes the test depending on the condition.

const nightclub = {
  dave: 26,
  sally: 23,
  mike: 17,
  lucy: 18,
}
const isOldEnough = Object.values(nightclub).every(el => el >= 18)
// false

if (!isOldEnough) {
  console.log("Check every ID")
}
Enter fullscreen mode Exit fullscreen mode

Let's connect

Twitter

đź’– đź’Ş đź™… đźš©
davidbell_xyz
David Bell

Posted on October 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related