Search code examples
javascriptreactjsobjectecmascript-6destructuring

Conditional Parameter addition to an Object Javascript


Following is my code, in which I am trying to add passStatus to an object only if it has a value otherwise omit it.

I tried this one - In Javascript, how to conditionally add a member to an object?

But seems like I am doing it wrong. Any pointers Please.

Code -

var a = {
  firstName: "Tom",
  lastName: "Simmon",
  email: "[email protected]",
  phone: "+36456",
  passStatus: "",
  query: "simple"
};

// var newObj = Object.assign(a, a.passStatus ? {a.passStatus} : null);

var newObj = {
   ...(a.passStatus? {passStatus: a.passStatus}: {} )
}

console.log(newObj); // {} <- Getting a blank object

Expected Output -

If passStatus = ""

{
  firstName: "Tom",
  lastName: "Simmon",
  email: "[email protected]",
  phone: "+36456",
  query: "simple"
}

If passStatus = "pass"

{
  firstName: "Tom",
  lastName: "Simmon",
  email: "[email protected]",
  phone: "+36456",
  passStatus: "pass",
  query: "simple"
}

Solution

  • I think the clearest way to conditionally remove a property from the object like this would be to use rest syntax followed by a possible Object.assign:

    var a = {
      firstName: "Tom",
      lastName: "Simmon",
      email: "[email protected]",
      phone: "+36456",
      passStatus: "",
      query: "simple"
    };
    
    const { passStatus, ...newObj } = a;
    if (passStatus) {
      Object.assign(newObj, { passStatus });
    }
    
    console.log(newObj);

    You can do it in one line by destructuring a computed property name, where the property name uses the conditional operator to remove the passStatus property if it exists - but this is hard to understand, I wouldn't recommend it:

    var a = {
      firstName: "Tom",
      lastName: "Simmon",
      email: "[email protected]",
      phone: "+36456",
      passStatus: "",
      query: "simple"
    };
    
    const { [a.passStatus ? '' : 'passStatus']: _, ...newObj } = a;
    console.log(newObj);