オブジェクトのキー一覧を取得
const test = { prop1: 'hoge', prop2: 'fuga' };
Object.keys(test); // ['prop1', 'prop2']
※オブジェクトのプロパティ参照順序は不定のため注意
オブジェクトの値一覧を取得
const test = { prop1: 'hoge', prop2: 'fuga' };
Object.values(test); // ['hoge', 'fuga']
オブジェクト配列からあるプロパティのみをピックアップ
const brothers = [
{id: 1, name: 'taro'},
{id: 2, name: 'jiro'},
{id: 3, name: 'saburo'},
];
brothers.map(brother=> brother.name); // ['taro', 'jiro', 'saburo']
オブジェクト配列から数値プロパティのみをピックアップし、すべて加算する
const brothers = [
{id: 1, name: 'taro', age: 32},
{id: 2, name: 'jiro', age: 28},
{id: 3, name: 'saburo', age: 18},
];
// 全員の年齢を加算
const sum = brothers.map(brother=> brother.age).reduce((prev, current) => prev + current);
// 平均年齢を算出
sum / brothers.length; // 26
オブジェクト配列から別の型のオブジェクト配列を生成
interface Student {
id: number;
name: string;
}
interface StudentWithClass extends Student {
class: string;
}
const students: Student [] = [
{id: 1, name: 'hanako'},
{id: 2, name: 'saburo'},
{id: 3, name: 'takumi'},
];
const className = '1年1組';
students.map<StudentWithClass>(s => ({id: s.id, name: s.name, class: className }));
/*
[
{id: 1, class: '1年1組', name: 'hanako'},
{id: 2, class: '1年1組', name: 'saburo'},
{id: 3, class: '1年1組', name: 'takumi'},
];
*/
map<変換後の型>
とすることで(s => ({}))
の記述時に補完機能が動いてくれるので、型セーフな変換が出来ます
時分秒文字列を時分に変換
const timeStr = '12:34:56';
timeStr.split(':').slice(0,2).join(':');
やってることは
-
:
で分割([時, 分, 秒]へ変換) - 配列の0,1のみを切り出し
- 再び
:
で結合
※時:分:秒形式でない場合は、元の文字列がそのまま返ります
事前にtimeStr.match(/^\d{2}:\d{2}(:\d{2}){0,1}$/)
とかでチェックしておいた方が安全です。