Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter the data with supported types in the response: JavaScript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading