-2

So I'm trying to check if an array of objects formatted like this:

const array = [
    {
     date: new Date(),
     userid: 123123
    },
    {
     date: new Date(),
     userid: 13222323
    },
   ...
]

So, I want to check if one of these objects contains a the current user id (of a user logged in), if the array of object contains it once, then return a Boolean value true, if not return false. I don't want to use some because it will return false and true, if there are other objects that do not have the same user id.

Joshua Bitton
  • 383
  • 2
  • 12
  • [Array#some()](https://mdn.io/array+some) – Thomas Apr 25 '21 at 22:49
  • for some reason, it is returning true and false based off of all the objects in the array, and therefore the code is being read, despite it being true (user id is included) once – Joshua Bitton Apr 25 '21 at 22:55

1 Answers1

0

with some

const array = [
  {
    date: new Date(),
    userid: 123123,
  },
  {
    date: new Date(),
    userid: 13222323,
  },
];

const loggedInUserId = 13222323;

const isExist = array.some(({ userid }) => userid === loggedInUserId);
if (isExist) {
  console.log("It exist");
} else {
  console.log("Doesn't exist");
}

with find: Find will return that particular object. If it is not then it will return undefined

const array = [{
    date: new Date(),
    userid: 123123,
  },
  {
    date: new Date(),
    userid: 13222323,
  },
];

const loggedInUserId = 13222323;

const isExist = array.find(({userid}) => userid === loggedInUserId);
if (isExist) {
  console.log("It exist");
} else {
  console.log("Doesn't exist");
}
DecPK
  • 24,537
  • 6
  • 26
  • 42