I have the following key StudentMembers[1].active
but I need to check if this key exist in the following array
const array= ["StudentMembers.Active","StudentMembers.InActive"]
How to remove the index [1]
from StudentMembers[1].active
and check if StudentMembers.Active
does exist in the array
CodePudding user response:
You can use regex to remove all brackets [<any>]
like this:
const key = "StudentMembers[1].active".replace(/\[.*\]/, '');
console.log(key); // Return "StudentMembers.active"
Then you can use .find()
to check if array contains the key
const array= ["StudentMembers.Active","StudentMembers.InActive"];
const hasKey = array.find(item => item.toLowerCase() == key.toLowerCase()) ? true : false;
console.log(hasKey); // Return true
It is strongly suggested to use .toLowerCase()
so it would match any kind of cases.
Example: https://jsfiddle.net/fhkx9v3n/