
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>
0Output:
{ 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.
Random Code Snippet Queries: Javascript
- How to set href value of anchor tag in javascript
- How to get file extension using javascript/jquery
- Concat variable with string in javascript
- How to make entire Div clickable in javascript
- On click enter redirect to another URL with parameters in javascript
- Remove property from object in javascript
- How to get data from localstorage in javascript
- How to crop multiple images with cropper js
- How to validate input type file size in javascript
- Short-circuits conditionals
- Get hostname from URL in javascript
- Animating numbers counting Javascript
- Execute function with condition in javascript
- Uncaught TypeError: Illegal invocation
- How to use JavaScript to search for items in a list
- How to remove duplicate values from array in javascript
- Hide div on click outside of element in javascript/jQuery
- Trim the leading and trailing comma from string in Javascript
- How to preview a word document in HTML using javascript
- Generate 6 digit random number in javascript
- Uncaught TypeError: Cannot read property 'addEventListener' of undefined
- How to check file is an image in javascript using filename
- Check if value exists in array javascript
- How to pass array as arguments to function in javascript
- Javascript get only 10 characters from string