0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでオブジェクトから特定のプロパティを削除する方法

Last updated at Posted at 2025-04-13

deleteを使う

deleteを使うと特定のプロパティを削除できます。

type SampleObject = {
  key1?: number;
  key2?: number;
  key3?: number;
  key4?: number;
  key5?: number;
}

const sampleObject: SampleObject = {
  key1: 1,
  key2: undefined,
  key3: 3,
  key4: 4,
  key5: undefined,
};

delete sampleObject.key2
console.log(sampleObject);
// {"key1": 1, "key3": 3, "key4": 4, "key5": undefined} 

delete sampleObject["key3"]
console.log(sampleObject);
// {"key1": 1, "key4": 4, "key5": undefined}

ただし、オプショナルでないプロパティをdeleteしようとすると下記のようなエラーになります。
Property 'key3' does not exist on type 'SampleObject'. Did you mean 'key'?

分割代入 + 残余引数を使う

プロパティの削除ではありませんが、分割代入と残余引数を使うと特定のプロパティを除いたオブジェクトを作ることができます。

const profile = {id: 1, name: 'hoge', age: 25, height: 170, weight: 65}
const {id, ...newProfile} = profile

console.log(id) // 1
console.log(newProfile)
// { "name": "hoge", "age": 25, "height": 170, "weight": 65 } 

分割代入と残余引数を使うことで、newProfileにはid以外のプロパティが格納されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?