[TypeScript]Object(オブジェクト)のプロパティを削除するには?

TypeScript

どうも、ちょげ(@chogetarou)です。

Object(オブジェクト)のプロパティ(property)を削除する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

Object(オブジェクト)のプロパティ(property)を削除するには、deleteを使います。

まず、deleteを記述します。

そして、deleteの右辺で、Objectのプロパティにアクセスします。

//prop=削除するプロパティ
delete obj.prop
//prop=削除するプロパティ
delete obj[prop]

上記のdeleteは、右辺でアクセスしたObject(オブジェクト)のプロパティ(property)を削除します。

使用例

type Numbers = {
    [key: string]: number
}

const nums: Numbers = { 
    "one": 1, 
    "two": 2,
    "three": 3,
    "four": 4,
    "five": 5,
}

delete nums.two
delete nums["five"]

console.log(nums)
出力:
{
  "one": 1,
  "three": 3,
  "four": 4
} 

コメント

タイトルとURLをコピーしました