0

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)
}
Thomas Jason
  • 538
  • 2
  • 7
  • 18
  • does this help? https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays – Max Jun 11 '20 at 08:49
  • You could have the keys that need encryption in an array, and iterate over it while modifying the object. – sp00m Jun 11 '20 at 08:49
  • To begin with, I'd put the `if` inside (a wrapper function around) the `encrypt` function. Then look at your code again and decide whether or not further steps are needed. Sometimes simple is better. – Ruud Helderman Jun 11 '20 at 09:01

3 Answers3

1
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]);
    }
});
Nikita Madeev
  • 4,284
  • 9
  • 20
1

You could collect wanted keys in an array and loop with the wanted condition.

['name', 'phone'].forEach(k => {
    if (company[k]) company[k] = encrypt(company[k]);
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use Object.keys to traverse through your object and encrypt,

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

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

Object.keys(company).map(function(key, index) {
  if (fieldsToEncrypt.indexOf(key) > -1 && company[key]) {
    company[key] = encrypt(company[key]);
  }
});
Ani
  • 370
  • 2
  • 9