How to add a property to object with condition in javascript

You can add property to object with condition in javascript. If the condition is true then it will add the property to object else it will not add the property to object.

Answers 1
  • Add a property to object with condition in javascript

    <script> 
    const condition = true
    
    const w3obj = {
      w3obj: 'w3codegenerator.com',
      ...condition && { name: 'samar' }
    }
    
    console.log(w3obj);
    </script>
    
    0

    Output:

    { w3obj: 'w3codegenerator.com', name: 'samar' }

    It will add the property ({ name:'samar' }) to object if the condition is true else it will not add the property to object. You can change the value of condition const with false and you can see output is different. 

  • Back to code snippet queries related javascript