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

登録したユーザーの名前が配列で取得されてしまう解決方法について

Posted at

はじめに

登録しているユーザーの名前を取得しようとしましたが、名前が配列で取得されてしまうため、そちらの解消方法について共有させていただきます。

下記のように記述していました。

const matchedName = users.
      filter((user) => user.user_id === searchUserId) // idが一致したユーザーを取得
      .map((user) => user.name); // その中の名前を取得

      setUserName(matchedName); // 取得した名前をセット

解決方法

こちらの記述で解決することができました。

.tsx
const matchedUser = users.find((user) => user.user_id === searchUserId); 
// ユーザーを1つずつ取り出し、idが一致した最初のユーザーを取得

const matchedName = matchedUser ? matchedUser.name : ""
// 取得したユーザーがあれば、その名前を取得

      setUserName(matchedName); // 取得した名前をセット

終わりに

map()を使っているため、配列string[]で取得されてしまっていました。


1
0
1

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