2

i was seeking for a solution like this in stackoverflow and in google but this is the idea

   a = {
  b: (conditionB? 5 : undefined),
  c: (conditionC? 5 : undefined),
  d: (conditionD? 5 : undefined),
  e: (conditionE? 5 : undefined),
  f: (conditionF? 5 : undefined),
  g: (conditionG? 5 : undefined),
 };

but i dont understand this... it doesnt work in nodejs i want to create an object a with many objects inside but if that objects are in the form send by the client

5 Answers 5

2

maybe what you want can be done using the array index notation?

a= {};
if(bla) a.b = "go";
Sign up to request clarification or add additional context in comments.

Comments

1

This can be achieved in 2 ways.

Either you use an if sentence for each conditional property as such:

    var a = {};
    if(conditionb){
      a.b = 5;
    }

Or if you don't want to create an if sentence for every property then you assign properties using the notation you presented in the question and then remove unnecessary ones in a loop:

    a = {
      b: (conditionB? 5 : undefined),
      c: (conditionC? 5 : undefined),
      d: (conditionD? 5 : undefined),
      e: (conditionE? 5 : undefined),
      f: (conditionF? 5 : undefined),
      g: (conditionG? 5 : undefined),
    };
    for(var i in a){
      if(a[i] === undefined){
        delete a[i];
      }
    }

Comments

1

Try this:

var a = {};
if(conditionB) {
   a['b'] = 5;
}

or

if(conditionB) {
   a.b = 5;
}

Comments

0

You Can try this,

var dog = d;

var myObject = {};
myObject['a']=(1<2)? 1 : 2;
myObject['b']=(1<2)? 1 : 2;
myObject['c']=(1<2)? 1 : 2;
myObject[dog]=(1<2)? 1 : 2;

Just in case you are creating the properties dynamically.

Comments

0

You can do this with ES2018:

a = {
  ...(conditionB? { b : 5} : {}),
  ...(conditionC? { c : 5} : {}),
};

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.