Ad

How To Refactor 'if' With Multiple Fields In JS

- 1 answer

There is an obejct that has many fields as below.

const company = { 
  "name": "app",
  "year": 1927,
  "car": "fox",
  "phone": "show"
}

And I want to encrypt some fields not all fields depends on condition.
But I have to 'if sentence' repeatdely.
Can I refactor this to avoid same if sentence that only has diferent field? Thank you for reading it.

if (company.name) {
   company.name = encrypt(company.name)
}
if (company.phone) {
   company.phone = encrypt(company.phone)
}
Ad

Answer

const company = {
    name: 'app',
    year: 1927,
    car: 'fox',
    phone: 'show',
};

const encryptFields = ['name', 'phone'];

encryptFields.forEach(f => {
    if (company[f]) {
        company[f] = encrypt(company[f]);
    }
});
Ad
source: stackoverflow.com
Ad