---
title: "JS 객체에 조건에 따라 동적으로 프로퍼티 추가하기"
date: "2022-04-24"
tags: ["TIL","JS"]
status: archived
verified: false
---

## JS 객체에 조건에 따라 동적으로 프로퍼티 추가하기

-   백앤드 서버에서 filter란 객체 값이 전달된 경우, SQL where 조건 객체를 만들기 위해 Object에 동적으로 프로퍼티를 추가하는 방법을 찾아 정리해 봄
-   처음엔 [Object.assign](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)을 이용하는 방법을 사용했으나 코드 길이가 길어져 가독성이 안좋았음

```js
const whereObj = {};

if (filter.user_id) {
  Object.assign(whereObj, {
    user_id: filter.user_id,
  });
}
if (filter.type) {
  Object.assign(whereObj, {
    type: filter.type,
  });
}
...
```

-   좀 더 간단한 방법이 없을까 찾아보니 스프레드 연산자를 활용한 방법이 있었음

```js
const whereObj = {
  ...(filter.user_id && { user_id: filter.user_id }),
  ...(filter.type && { type: filter.type }),
};
...
```

### 참고

-   [stackoverflow - In JavaScript, how to conditionally add a member to an object?](https://stackoverflow.com/a/40560953)
