I am trying to not submit the data if a user is passing unsupported values.
Somehow my if the condition is getting executed for unsupported type too.
Explanation:
Here, the response gave the supported type as create and delete.
so allowed data can be only ‘A’ and ‘D’.
If the user passes ‘C’, I would like to break the loop and show the user that they entered invalid data.
let res = {
'create': true,
'edit': false,
'delete': true,
};
const valMapper = {
'A': 'create',
'C': 'edit',
'D': 'delete',
};
values = ['A', 'C', 'D'];
values.forEach((data) => {
if (res.hasOwnProperty(valMapper[data])) {
console.log(data);
} else {
//return or break as the data is submitted which doesn't match the res values
}
});
>Solution :
You need to check if you have the key in the first object and then you need to check to see if it is true or false. You are only doing the first check, you never check the state in res.
let res = {
'create': true,
'edit': false,
'delete': true,
};
const valMapper = {
'A': 'create',
'C': 'edit',
'D': 'delete',
};
function testValue(values) {
values.forEach((data) => {
const action = valMapper[data]
if (action) {
const isEnabled = res[action];
if (isEnabled) {
console.log("inside", data);
} else {
throw new Error(`The action '${action}' is disabled`);
}
} else {
throw new Error(`Unknown parameter '${data}'`);
}
});
}
function test(values) {
console.group("test");
try {
testValue(values);
console.log("done");
} catch (e) {
console.log(e.message);
}
console.groupEnd("test");
}
test(["A"]);
test(["A","D"]);
test(["A", "C"]);
test(["A", "B"]);