3

How do I search for a specific value in an array of objects based on another value? For example, I have the ID of a post and want to check if I have the required permissions for that particular Post ID.

Posts = [
    {
      Id: '123',
      Permission: 'True',
      Name: 'XY'
      //Other key value pairs
     },
    {
      Id: '456',     
      Permission: 'False'
      Name: 'AB'
      //Other key value pairs
    } 
];

My current approach goes in this direction.

if (posts.some(e => e.Permission === true && e.Id == PostId)) {
        return true;
      } else {
        return false ;
      }

I appreciate any support.

dan_boy
  • 1,735
  • 4
  • 19
  • 50
  • sounds like [find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) is what you need? – richytong Jun 26 '20 at 15:52

2 Answers2

3

To find the element

const arr = arr.find(p => p.property == someValue);

This will return undefined if the element is not found and return the element if found.

To find the index of the element

If you only want the index use findIdex

const index = arr.findIndex(p => p.property == someValue);

If the element is not found it will return -1 and if found return the index.

To check if the element is present i.e bool value

Your current implementation does that. You can simply return that.

return posts.some(e => e.Permission === true && e.Id == PostId)

Seems like you are confusing with how to use the value from somewhere else to search in the array, you can always pass in a callback and check that.

value => value.somProp == value1 && value.otherProp == value2 || someOtherChek(value)
Subesh Bhandari
  • 1,062
  • 1
  • 10
  • 21
  • 1
    Thanks @Subesh. You are right, I confused that 'e.Id' is case sensitive. After correcting it, everything works. – dan_boy Jun 28 '20 at 08:45
0

you can use filter

Posts = [
{
  Id: '123',
  Permission: 'True',
  Name: 'XY'
  //Other values
 },
{
  Id: '456',     
  Permission: 'False'
  Name: 'AB'
  //Other values
} 

];

let id='123';
let filtered=Posts.filter(i=> i. Permission===true && i.Id===id);
Nonik
  • 645
  • 4
  • 11