0
function a (METRIC,DIMENTIONS){
  var args = {
     'ids': ids,
     'start-date': START_DATE,
     'end-date': END_DATE,
     'metrics': METRIC,
     'dimensions': DIMENTIONS
  };
}

I have this array in javascript where dimensions is an optional value i want to check if DIMENTIONS is an empty string i want my args to look like this :

var args = {
     'ids': ids,
     'start-date': START_DATE,
     'end-date': END_DATE,
     'metrics': METRIC
  };

i tried this :

var args = {
     'ids': ids,
     'start-date': START_DATE,
     'end-date': END_DATE,
     'metrics': METRIC,
    DIMENTIONS!=''? 'dimensions': DIMENTIONS : ''
  };

but this will keep the , after METRIC and will produce an error

Technotronic
  • 8,424
  • 4
  • 40
  • 53
Sora
  • 2,465
  • 18
  • 73
  • 146

3 Answers3

2
if( !args.dimensions )
 delete args.dimensions;

That's about it :)

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
1

naive and simple solutuion:

function a (METRIC,DIMENTIONS){
  var args = {
     'ids': ids,
     'start-date': START_DATE,
     'end-date': END_DATE,
     'metrics': METRIC
  };
  
  if(DIMENTIONS) {
  args['dimensions']   = DIMENTIONS;
  }
}
Navaneeth
  • 2,555
  • 1
  • 18
  • 38
1

Do not add this key in object initially. Check if is a valid value then add it!

var args = {
  'ids': ids,
  'start-date': START_DATE,
  'end-date': END_DATE,
  'metrics': METRIC
};
if (typeOf DIMENTIONS !== 'undefined') {
  args.dimensions = DIMENTIONS;
}
Rayon
  • 36,219
  • 4
  • 49
  • 76