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

5
  • why dont to move it out of object literal? Commented Dec 3, 2015 at 7:27
  • What did you already try? Commented Dec 3, 2015 at 7:28
  • 1
    i said it in my post man Commented Dec 3, 2015 at 7:29
  • Possible duplicate of How to remove a property from a JavaScript object Commented Dec 3, 2015 at 7:30
  • No it is not a duplicate. He does not want to include dimension if DIMENTIONS are empty. Commented Dec 3, 2015 at 7:33

3 Answers 3

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

That's about it :)

Sign up to request clarification or add additional context in comments.

4 Comments

but how did we check if DIMENTION is null ?
You said you wanted to check if it is an empty string, this code makes that check
You include it and then delete it. That is not optimal
I don't, OP does :) You're right they shouldn't be doing that. Guess i focused on the question title mostly
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;
  }
}

1 Comment

Beat me by 11 secs - you may want to have dimentions if they are 0
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.