I have a below snippet, here I am using array.find to find the first success case and end it. So here is the code snippet
const USERS_LIST = [
{
key: "john",
location: "dublin",
},
{
key: "joe",
subKeys: [
{
key: "jane",
locaction: "washington",
},
{
key: "mary",
location: "newyork",
},
],
},
{
key: "chris",
location: "amsterdam",
},
];
so what I am trying here is I go through each object in USERS_LIST and check for a subKeys property. If a subKeys property is present, loop through that and check whether that key is eligible. If it's eligible then I need to stop it or it will pass to the next subkey. If I don't find any subKeys eligible then iterate to the next USERS_LIST object then it takes the key and checks for eligible, whichever I find the first I do a callback and stop executing.
I am able to solve this with this snippet
USERS_LIST.find((user) => {
if (user?.subKeys) {
user.subKeys.find((subUser) => {
let subUserStatus = checkEligible({
action: subUser.key,
});
if (subUserStatus) {
callback(subUser.location);
return true;
}
return false;
});
} else {
let userAccess = checkEligible({ action: user.key });
if (userAccess) {
callback(user.location);
return true;
}
}
return false;
});
Is there a better way using with array.some or any other functions where I can achieve the same output.
USERS_LIST.find()is ultimately used, as well as definingcallbackandcheckEligible. Please read this meta post for more information. \$\endgroup\$