Logo
Published on

Conditionally Add Object to Array in Typescript

Introduction

typescript-array

TypeScript offers powerful features for manipulating arrays and objects. One common task developers face is conditionally adding objects to arrays.

This technique can be particularly useful when working with dynamic data or implementing complex logic in your applications.

Let's explore various methods to achieve this in TypeScript, along with their pros and cons.

Table of Contents

Using the Spread Operator

The spread operator is a concise way to conditionally add objects to arrays.

Basic Example

const baseArray = [1, 2, 3]
const condition = true
const newObject = 4

const result = [...baseArray, ...(condition ? [newObject] : [])]
console.log(result) // [1, 2, 3, 4]

This method is clean and easy to read for simple conditions.

Multiple Conditions

You can extend this approach for multiple conditions:

const baseArray = ['apple', 'banana']
const condition1 = true
const condition2 = false

const result = [...baseArray, ...(condition1 ? ['cherry'] : []), ...(condition2 ? ['date'] : [])]

console.log(result) // ['apple', 'banana', 'cherry']

Using Array.push() Method

For more complex logic, you might prefer using the push() method.

Single Condition

const fruits: string[] = ['apple', 'banana']
const addOrange = true

if (addOrange) {
  fruits.push('orange')
}
console.log(fruits) // ['apple', 'banana', 'orange']

Multiple Conditions with Objects

interface Fruit {
  name: string
  color: string
}

const fruits: Fruit[] = [
  { name: 'apple', color: 'red' },
  { name: 'banana', color: 'yellow' },
]

const addOrange = true
const addGrape = false

if (addOrange) {
  fruits.push({ name: 'orange', color: 'orange' })
}

if (addGrape) {
  fruits.push({ name: 'grape', color: 'purple' })
}

console.log(fruits)
// [
//   { name: 'apple', color: 'red' },
//   { name: 'banana', color: 'yellow' },
//   { name: 'orange', color: 'orange' }
// ]

Using Array.concat() Method

The concat() method offers another approach to conditionally add objects.

const baseArray = [1, 2, 3]
const condition = true
const newObject = 4

const result = baseArray.concat(condition ? [newObject] : [])

console.log(result) // [1, 2, 3, 4]

This method is useful when you want to create a new array without modifying the original.

When working with large arrays or frequent operations, consider the performance implications of each method.

MethodProsCons
SpreadConcise, readableCreates new array
push()Modifies existing arrayCan be verbose with multiple conditions
concat()Creates new arraySlightly less performant for large arrays

Choose the method that best fits your specific use case and coding style.