DEV Community

loading...

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

davidbell_space profile image David Bell Originally published at davidbell.space ・1 min read

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

Discussion

pic
Editor guide