Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140101

using spread syntax with ternary operator inside object literal

$
0
0

Consider following code, where one object is composed from two parts: values and their corresponding descriptions:

let flagConfigObj = {};

const features = {
  f1: {
    value: 1,
    type: 'type1'
  },
  f2: {
    value: 2,
    type: 'type2'
  }
};

let featuresDescription = {
  f1: {
    description: 'desc 1'
  },
  f2: {
    description: 'desc 2'
  }
};

Object.keys(features).forEach(key => {
  flagConfigObj[key] = {
    ...features[key],
    ...(featuresDescription[key] || { some: 'backup' })
  };
});

console.log(flagConfigObj);

As you might notice, when composite is constructed, there is || operator preventing form spreading non-existing object and replacing it with some default templates. And so, output for this code will be:

{ 
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', description: 'desc 2' } 
}

But when corresponding description field in featuresDescription is missing, it's replaced to:

{ 
  f1: { value: 1, type: 'type1', description: 'desc 1' },
  f2: { value: 2, type: 'type2', some: 'backup' } 
}

The question

How to replace || syntax with ternary operator ?:? I've tried some funny combinations like

featuresDescription[key] ? ...featuresDescription[key] : {some: 'backup'}
{featuresDescription[key]} ? ...featuresDescription[key] : {some: 'backup'}

But all of them gives syntax error, and I'm feeling now like just blindly randomizing positions of [,],},{,... instead of truly understanding it...

Any help as always is appreciated!


Viewing all articles
Browse latest Browse all 140101

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>