how i can true and false a value with ternary operator if that value is present or not in an array

101 Views Asked by At

i want an array of object with some properties and want to check that object have particular property or not and moreover i also want if that object dosn't have that property in an array then return false if present then return true but i never wanna use if else statement i want to do it with ternary operator but i have some issue in below code inside a function.

let users = {
  Alan: {
    age: 27,
    online: true
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: true
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function isEveryoneHere(obj) {

  return (users.Alan) ? true : (users.Jeff) ? true : (users.Ryan) ? true : (users.Sarah) ? true : false;

}

console.log(isEveryoneHere(users));

1

There are 1 best solutions below

3
Emil S. Jørgensen On

There is a lot to unpack here, but lets start with your user list.

When you store a list it is usually best to use an Array, as this will give you access to the array methods like every.

Moving the "name" into the objects makes it nicely conform to array syntax, and you could use find to get entries by name anyway.

Secondly, now that we have array methods, the ternary approach is redundant. We simply ask if every object in the list has a true online property. Doing it this way greatly increases readability of your code, and saves us from constantly reinventing existing solutions.

Here is an example of the above points:

var users = [{
  name: 'Alan',
  age: 27,
  online: true
}, {
  name: 'Jeff',
  age: 32,
  online: true
}, {
  name: 'Sarah',
  age: 48,
  online: true
}, {
  name: 'Ryan',
  age: 19,
  online: true
}];

function isEveryoneHere(users) {
  return users.every(function(user) {
    return user.online;
  });
}
console.log(isEveryoneHere(users));