🔑

TypeScriptで、オブジェクトから値を取り出す

2024/08/25に公開

🔅Tips

データ型をつけたオブジェクトから、値を抽出する方法がまだまだよくわかっていないので、試してみた。
やってることはこのDartの記事と同じです。

Objectの中にcountryというkeyがあるかどうかを確認

  1. type Memberを定義
  2. hasOwnPropertyでオブジェクトが存在するか確認
function main() {
  const members = [
    { name: "Roko", age: 26, height: 170.0, weight: 50.0 },
    { name: "Mako", age: 24, height: 160.0, weight: 45.0 },
    { name: "Miki", age: 22, height: 150.0, weight: 40.0 },
    { name: "Nana", age: 20, height: 140.0, weight: 35.0 },
    { name: "Yuko", age: 18, height: 130.0, weight: 30.0 },
    { name: "Yoko", age: 16, height: 120.0, weight: 25.0 },
    { name: "Mako", age: 14, height: 110.0, weight: 20.0 },
    { name: "Yuko", age: 12, height: 100.0, weight: 15.0, country: "Japan" },
  ];

  /**
   * @param {Member[]} members
   * data type Member[] は、以下のように定義されています
   * type Member = {
   *    name: string;
   *    age: number;
   *    height: number;
   *    weight: number;
   *    country?: string;
   * };
   * @param {boolean} hasOwnProperty
   *  https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
   *  hasOwnProperty() メソッドは、指定されたプロパティがオブジェクトに存在するかどうかを返します。
   */

  type Member = {
    name: string;
    age: number;
    height: number;
    weight: number;
  };

  const keyCountry: Member[] = [];

  // for文でmembersをloop
  for (const m of members) {
    console.log(m);
    // {name: Roko, age: 26, height: 170.0, weight: 50.0}
    // {name: Mako, age: 24, height: 160.0, weight: 45.0}
    // {name: Miki, age: 22, height: 150.0, weight: 40.0}
    // {name: Nana, age: 20, height: 140.0, weight: 35.0}
    // {name: Yuko, age: 18, height: 130.0, weight: 30.0}
    // {name: Yoko, age: 16, height: 120.0, weight: 25.0}
    // {name: Mako, age: 14, height: 110.0, weight: 20.0}
    // {name: Yuko, age: 12, height: 100.0, weight: 15.0, country: Japan}
    console.log("-----------------------------------------------------");
    // Objectの中にcountryというkeyがあるかどうかを確認
    if (m.hasOwnProperty("country")) {
      // keyCountryにcountryというkeyがあるMapを追加
      keyCountry.push(m);
    }
  }

  console.log(keyCountry);
  // [{name: Yuko, age: 12, height: 100.0, weight: 15.0, country: Japan}]
}

main();

keyword検索をする

  1. filterメソッドを使って、labelに指定した文字列が含まれるMemberを返す
  2. includesメソッドは、文字列が含まれているかどうかを確認する
type Member = {
    name: string;
    age: number;
    height: number;
    weight: number;
    label: string;
    country?: string;
};

const members: Member[] = [
    { name: "Roko", age: 26, height: 170.0, weight: 50.0, label: "88" },
    { name: "Nick", age: 28, height: 180.0, weight: 70.0, label: "1111" },
    { name: "Aya", age: 18, height: 160.0, weight: 40.0, label: "aaa" },
    { name: "John", age: 30, height: 160.0, weight: 60.0, label: "jjj" },
    { name: "Rui", age: 30, height: 170.0, weight: 60, label: "333" },
];

function searchKeyword(value: string): Member[] {
    return members.filter(m => m.label.includes(value));
}

function main() {
    let result = searchKeyword("aa");
    if (result.length > 0) {
        result.forEach(member => console.log(member));
    } else {
        console.log("Not Found");
    }

    // {name: Aya, age: 18, height: 160.0, weight: 40.0, label: aaa}

    result = searchKeyword("1");
    if (result.length > 0) {
        result.forEach(member => console.log(member));
    } else {
        console.log("Not Found");
    }

    // {name: Nick, age: 28, height: 180.0, weight: 70.0, label: 1111}
}

main();

sortで配列を並び替える

Dartみたいに、compareToがないので、b.height - a.heightで値を計算する処理が必要だった。

function main() {
    type Member = {
        name: string;
        age: number;
        height: number;
        weight: number;
        country?: string
    }

    const members: Member[] = [
        { name: "Aya", age: 18, height: 160.0, weight: 40.0 },
        { name: "John", age: 20, height: 160.0, weight: 60.0, country: "🇺🇸" },
        { name: "Rui", age: 50, height: 170.0, weight: 60.0, country: "🇬🇧" },
    ];

    /**
     * sortメソッドを使って、heightが大きい順に並べる
     * 同じなら、ageが大きい順に並べる
     * b.height - a.height は、heightが大きい順に並べる
     */

    // sortメソッドを使って、heightが大きい順に並べる
    // 同じなら、ageが大きい順に並べる
    members.sort((a, b) => {
        const heightComparison = b.height - a.height;
        // !== 0 は、heightComparisonが0でない場合
        if (heightComparison !== 0) return heightComparison;
        return b.age - a.age;
    });

    console.log(members);

    // [{name: Rui, age: 50, height: 170.0, weight: 60.0, country: 🇬🇧}, {name: John, age: 20, height: 160.0, weight: 60.0, country: 🇺🇸}, {name: Aya, age: 18, height: 160.0, weight: 40.0}]
}

main();

まとめ

パターンは様々なので、オブジェクトや配列は操作するロジックを書いてみて、理解するしかないです。過去に書いた記事も参考までにみて下さい。

https://zenn.dev/joo_hashi/articles/b768de4d3bb9ec
https://zenn.dev/joo_hashi/articles/03d8e591447d73

Discussion