Javascript

[JavaScript] 개체 또는 배열에 조건부로 추가

헝그리코더 2022. 6. 7. 18:57

The logical && (AND) operator

const trueCondition = true;
const falseCondition = false;

const obj = {
  ...(trueCondition && { dogs: "woof" }),
  ...(falseCondition && { cats: "meow" }),
};

// { dogs: 'woof' }

const arr = [
  ...(trueCondition ? ["dog"] : []),
  ...(falseCondition ? ["cat"] : [])
];

// ['dog']

The spread operator (...)

let myDogs = [`Riggins`, `Lyla`];
let parentsDogs = [`Ellie`, `Remi`];

const holidayDoghouse = [...myDogs, ...parentsDogs];
// [ 'Riggins', 'Lyla', 'Ellie', 'Remi' ]
let existingAnimals = {
  dogs: 2,
  cats: 4,
  donkeys: 2,
  horses: 2,
};

let newAnimals = {
  goats: 2,
};

const allAnimals = {
  ...existingAnimals,
  ...newAnimals,
};
// { dogs: 2, cats: 4, donkeys: 2, horses: 2, goats: 2 }