> For the complete documentation index, see [llms.txt](https://asad-razvi.gitbook.io/javascript-cookbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://asad-razvi.gitbook.io/javascript-cookbook/object-recipes/how-can-i-conditional-add-a-key-value-into-an-object.md).

# How can I conditionally add a key-value into an object?

```javascript
// Approach1: How to conditionally add key-value pairs into an object
const a = {}
const x = 'happy'
const y = undefined
if (x) {
  a[x] = x
}
if (y) {
  a[y] = y
}
console.log('The value of a is ', a)

// Approach2: How to conditionally add key-value pairs into an object
const p = 'happy'
const q = undefined
const b = { ...( p ? { p } : { } ), ...( q ? { q } : { } )}
console.log('The value of b is ', b)
```
