简体   繁体   中英

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?

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;
}, {});

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM