0

Use-Case: I would like to go through the array of objects, checking each action until one of the actions equals a specific array [ 'sqs:GetQueueAttributes', 'sqs:GetQueueUrl', 'sqs:SendMessage' ],.

I understand, however, I cannot use the === after reading this question.

Array:

[
    {
      Action: [
        'logs:CreateLogDelivery',
      ],
    },
    {
      Action: [ 'sqs:GetQueueAttributes', 'sqs:GetQueueUrl', 'sqs:SendMessage' ],
      Effect: 'Allow',
      Resource: {
        'Fn::ImportValue': 'XXXXXX"
      }
    }

]

How can I do it so I can return true or false?

Luke
  • 761
  • 1
  • 18

4 Answers4

2

Check if some() filters has every() Action includes() in the array

const search  = [ 'sqs:GetQueueAttributes', 'sqs:GetQueueUrl', 'sqs:SendMessage' ];
const filters = [
    { Action: ['logs:CreateLogDelivery'] },
    { Action: [ 'sqs:GetQueueAttributes', 'sqs:GetQueueUrl', 'sqs:SendMessage' ], Effect: 'Allow', Resource: {'Fn::ImportValue': 'XXXXXX'} }
];

const searchIsInSomeFilter = filters.some(filter => {
    return search.every(searchValue => {
        return filter.Action.includes(searchValue);
    });
});

console.log(searchIsInSomeFilter);

// One-liner with short return:
// const searchIsInSomeFilter = filters.some(filter => search.every(searchValue => filter.Action.includes(searchValue)));
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    This answer is great! Could you clean up the ";;", make `f` and `s` more descriptive, and add some notes for other readers to easily understand? I'll mark it as the answer for this question. – Luke Feb 16 '23 at 15:46
  • Yea Ill apply those changes! - I hope this is better! – 0stone0 Feb 16 '23 at 15:50
0

you can use the function Array.includes on an array to know if a given string is present or not.

ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Bearmit
  • 9
  • 2
0

I'd just make a function to compare two Arrays.

const array = [
    {
      Action: [
        'logs:CreateLogDelivery',
      ],
    },
    {
      Action: [ 'sqs:GetQueueAttributes', 'sqs:GetQueueUrl', 'sqs:SendMessage' ],
      Effect: 'Allow',
      Resource: {
        'Fn::ImportValue': 'XXXXXX'
      }
    }
];

function checkArr(arr, actions) {
  for (const obj of arr) {
    if (isArrayEqual(obj.Action, actions)) {
      return true
    }
  }
  return false
}

function isArrayEqual(a, b) {
  for (const aa of a) {
    if (!b.includes(aa)) {
      return false
    }
  }
  for (const bb of b) {
    if (!a.includes(bb)) {
      return false
    }
  }
  return true
}

console.log(checkArr(array, ['sqs:GetQueueAttributes', 'sqs:GetQueueUrl', 'sqs:SendMessage']));
twharmon
  • 4,153
  • 5
  • 22
  • 48
0

Deep equality checks the depths of objects so that every child (and child's child, etc.) is equal to the other. You can write your own, but many libraries exist to solve this problem. Here are some solutions:

msenne
  • 613
  • 5
  • 8