Dys
Dys

Reputation: 3

Shorter if statement in Javascript

I'm newbe in Js I wanna check to statuses have same value:

if (data.a_status == 'approved' && data.b_status == 'approved' && data.c_status == 'approved')

Can I write this shorter? I can't find any material how to check same value in three variables

Upvotes: 0

Views: 96

Answers (1)

Francis Leigh
Francis Leigh

Reputation: 1960

If you know the exact properties you want to access from data, put them into an array and access them via square bracket notation within an every loop against the data Object.

const data = {
  a_status : 'approved', 
  b_status : 'approved', 
  c_status : 'approved',
  foo: 'bar',
  hello: 'world'
}

const statuses = ['a_status', 'b_status', 'c_status']

const approved = statuses.every(s => data[s] === 'approved')

console.log(approved)

Upvotes: 6

Related Questions