1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

オブジェクトの特定のプロパティ以外を全て取り出す方法

Last updated at Posted at 2025-05-03

分割代入と残余引数を使えば、オブジェクトから「特定のプロパティ以外」を全て取り出すことができます。

const profile = {
  id: 1,
  name: "hoge",
  age: 30,
  gender: "man",
  height: 165,
  weight: 55,
  bloodType: "O"
}

const {id, ...newProfile} = profile;
console.log(newProfile);
// {"name": "hoge", "age": 30, "gender": "man", "height": 165, "weight": 55, "bloodType": "O"} 

上の例では、オブジェクトprofileからidを分割代入で取り出し、それ以外のプロパティは残余引数を使ってnewProfileで取り出しています。

Reactでは、「propsの特定のプロパティ以外をそのまま別のコンポーネントに渡す」ときなんかに使えます。

以下の例では、HogeButtonコンポーネントにpropsでbuttonName、onClick、disabledを渡しています。

HogeButtonコンポーネントではbuttonNameを分割代入で取り出し、それ以外は残余引数でhogeButtonPropsとして取り出しています。

そして、Buttonコンポーネントに対してbuttonNameを渡し、それ以外はhogeButtonPropsをスプレッド構文で展開して渡しています。

"use client"

import HogeButton from "@/components/HogeButton";

export default function Home() {
  return (
    <HogeButton
      buttonName="hoge"
      onClick={() => {
        alert("hoge");
      }}
      disabled={false}
    />
  );
}
import { ButtonHTMLAttributes } from "react";
import Button from "./Button";

type HogeButton = {
  buttonName: string;
} & ButtonHTMLAttributes<HTMLButtonElement>;

const HogeButton = (props: HogeButton) => {
  const { buttonName, ...hogeButtonProps } = props;
  return <Button buttonName={buttonName} {...hogeButtonProps} />;
};

export default HogeButton;
import { ButtonHTMLAttributes } from "react";

type Button = { buttonName: string } & ButtonHTMLAttributes<HTMLButtonElement>;

const Button = (props: Button) => {
  const { buttonName, ...buttonProps } = props;
  return <button {...buttonProps}>{buttonName}</button>;
};

export default Button;

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?