Sharif Mamun
Sharif Mamun

Reputation: 3554

How to conditionally update properties of an object?

I have an object named options. I need to do something like below where if a property is already set, update it otherwise don't do anything:

if (options.A)
    options.A = formatMessage(options.A);
if (options.B)
    options.B = formatMessage(options.B);
if (options.C)
    options.C = formatMessage(options.C);
if (options.D)
    options.D = formatMessage(options.D);

Is there a better way to check if a particular property of an object is set and then update in pure JavaScript?

Upvotes: 3

Views: 346

Answers (2)

Geeky
Geeky

Reputation: 7498

You can consider this option

 const obj = {
 'A':'test','B':'test1','C':'test2','D':'test3'
 };
    
 Object.keys(obj).map(key=> {
   obj[key]=formatMessage(obj[key]);
 });
 
 function formatMessage(msg){
 return msg + 'translated';
 }
 
 console.log(obj);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370689

Iterate over an array of key names - if the retrieved value at each key is truthy, call the function and reassign it:

['A', 'B', 'C', 'D'].forEach((key) => {
  if (options[key]) {
    options[key] = formatMessage(options[key]);
  }
});

If these are the only keys that might exist, you might consider using .reduce into a new object instead, thereby avoiding unnecessary mutation:

const formattedOptions = Object.entries(options).reduce((a, [key, val]) => {
  a[key] = formatMessage(val);
  return a;
}, {});

Upvotes: 2

Related Questions