개발 기술/사소하지만 놓치기 쉬운 개발 지식

[JS] array, object에 조건부로 값을 추가하는 간단한 방법(with. &&, spread 연산자)

by GicoMomg (Lux) 2022. 6. 11.

🙂 이번 시간에는 array, object에 조건부로 특정 값을 추가하는 간단한 방법에 대해 알아보았다!


1. array에 조건부로 값을 추가하는 간단한 방법

  • 만약 arr에서 hasLegtrue일 때 cat을 원소로 추가한다고 하자.
  • 먼저, if를 사용해 값을 추가하는 방법이 있다.
const hasLeg = true;
const arr = ['dog', 'horse'];

if (hasLeg) arr.push('cat');

console.log(arr); // ['dog', 'horse', 'cat']

🤔 하지만 좀 더 간단한 방법으로 원소를 추가하고 싶은데 방법이 없을까? spread 연산자(…)와 &&연산자를 사용하면 된다!

(1) 값을 하나만 추가하는 경우

  • &&연산자(A && B)는 A가 true이면 B값을, A가 false이면 A값을 반환한다.
true && '안녕';    // '안녕'
false && '안녕';   // false

  • 우리는 hasLegtrue일 때 catarr에 추가하고 싶으니, hasLeg && 'cat'으로 구성한다.
hasLeg && 'cat';    // 'cat'

  • 그 다음, arr에 해당 구문을 추가해주기만 하면 된다.
const hasLeg = true;
const arr = ['dog', 'horse', hasLeg && 'cat'];

console.log(arr); // ['dog', 'horse', 'cat']

(2) 여러 값을 추가하는 경우

  • 만약 하나의 원소가 아닌 여러 원소를 추가하고 싶다면 spread 연산자를 사용해야 한다.
  • hasLegtrue일 때, arr에 cat, rat을 추가하고자 한다.
  • 먼저, &&연산자를 이용해 아래와 같이 구성해준다.
hasLeg && ['cat', 'rat'];    // ['cat', 'rat']

  • 그 다음에 이 배열의 원소를 arr에 넣어야 하므로 spread연산자(…)를 이용해준다.
const hasLeg = true;
const arr = ['dog', 'horse', ...(hasLeg && ['cat', 'rat'])];

console.log(arr); // ['dog', 'horse', 'cat', 'rat']



2. object에 조건부로 값을 추가하는 간단한 방법

  • 만약 obj에서 hasLicensetrue일 때, { driveEnabled: true }을 추가하고자 한다.
  • if를 사용하면 아래와 같이 값을 추가할 수 있다.
const hasLicense = true;
const obj = { name: 'Lila', age: 22 }; 

if (hasLicense) obj['driveEnabled'] = true;

console.log(obj); // { name: 'Lila', age: 22, driveEnabled: true }

😊 array에서 사용했던 것처럼 간단한 방법으로 키값을 추가하고 싶다면, spread 연산자(…)와 &&연산자를 사용하자!

(1) 값을 추가하는 경우

  • obj에 키:값 쌍을 추가하려면 spread, &&연산자 두 가지를 모두 사용해야한다.
hasLicense && { driveEnabled: true };    
const hasLicense = true;
const obj = { 
  name: 'Lila', 
  age: 22, 
  ...(hasLicense && { driveEnabled: true })
}; 

console.log(obj); 
// { name: 'Lila', age: 22, driveEnabled: true }

  • 만약 두 개의 키:값 쌍을 추가한다고 하면, 위 방식과 똑같이 하면 된다.
hasLicense && { driveEnabled: true, carPurchasable: true };
const hasLicense = true;
const obj = { 
  name: 'Lila', 
  age: 22, 
  ...(hasLicense && { driveEnabled: true, carPurchasable: true })
}; 

console.log(obj); 
// { name: 'Lila', age: 22, driveEnabled: true, carPurchasable: true }

반응형

댓글