flinch85
flinch85

Reputation: 370

How to check if any item in object matches any key in other array

I want to see if any item in arr2 matches any top level key from arr1 (forms or assets).

First array:

const arr1 = {
  forms: {
    permissions: {
      create: true,
      edit: true,
      delete: true,
    },
  },
  assets: {
    permissions: {
      create: true,
      edit: true,
      delete: true,
    },
  },
};

Second array:

const arr2 = ["assets", "media"];

I have tried this:

if (arr2 in arr1) {
    console.log("key is in contained in object");
}

But this only works when there is only one item in arr2.

Upvotes: 1

Views: 1098

Answers (2)

Ben Aston
Ben Aston

Reputation: 55729

For the array use Array#some with a test using Object#hasOwnProperty.

For objects, you don't need to enumerate the keys of the object (O(n)): you can perform a direct test for the presence of a key (O(1)).

const o = {
  forms: {
    permissions: {
      create: true,
      edit: true,
      delete: true,
    },
  },
  assets: {
    permissions: {
      create: true,
      edit: true,
      delete: true,
    },
  },
}

const arr = ["assets", "media"]

console.log(arr.some((k) => o.hasOwnProperty(k))) // true

Upvotes: 2

Alex Gourlay
Alex Gourlay

Reputation: 385

You can get an array of the object's top level keys and then check if any of them are included in the other array.

Like so:

const arr1 = {
  forms: {
    permissions: {
      create: true,
      edit: true,
      delete: true,
    },
  },
  assets: {
    permissions: {
      create: true,
      edit: true,
      delete: true,
    },
  },
};

const arr2 = ["assets", "media"];

function hasSomeTopLevelKey(object, arrayOfKeys) {
   return Object.keys(object)
   .some(topLevelKey => arrayOfKeys.includes(topLevelKey));
}

const x = hasSomeTopLevelKey(arr1, arr2)
console.log(x)

Upvotes: 1

Related Questions