简体   繁体   中英

how to conditionally create a member inside an object in javascript?

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

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

a= {};
if(bla) a.b = "go";

Try this:

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

or

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

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];
      }
    }

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.

You can do this with ES2018:

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

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