Open6
TypeScript CodeSnippets
配列内のオブジェクトから要素を検索する
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const res = inventory.find( ({ name }) => name === 'cherries' );
console.log(res) // { name: 'cherries', quantity: 5 }
配列内の各オブジェクトにプロパティを追加する
const items = [{name: 'apples'}, {name: 'bananas'}, {name: 'cherries'}]
const inventory: inventory[] = items.reduce((acc, item) => {
const res = [
...acc,
{
name: item.name,
quantity: getQuantity(item.name),
} as inventory
]
return res
}, [] as inventory[])
console.log(inventory) // [{"name": "apples", "quantity": 100}, {...}]
オブジェクトの配列をオブジェクトに変換する
const items = [{name: 'apples'}, {name: 'bananas'}, {name: 'cherries'}]
const res = {...items}
console.log(res)
// {"0": {name: 'apples'}, "1": {name: 'bananas'}, "2": {name: 'cherries'}}
オブジェクトの配列から重複する要素を削除し配列に変換する
const items = [{name: 'apples'}, {name: 'bananas'}, {name: 'apples'}]
const res = items.map((v) => v.name).filter((val, index, self) => self.indexOf(val) === index)
console.log(res) // ["apples", "bananas"]
const items = [{name: 'apples'}, {name: 'bananas'}, {name: 'apples'}]
const res = [...new Set(items.map((v) => v.name))]
console.log(res) // ["apples", "bananas"]
undefinedを除外した配列の型からundefinedを取り除く
const items = items.filter(
(item): item is Exclude<typeof item, undefined> => item !== undefined
)
条件によって値を返す処理色々
if
let quantity = 0
if (item === items.apples) {
quantity = 10
} else if (item === items.bananas) {
quantity = 8
}
switch-case
let quantity = 0
switch (item) {
case items.apples:
quantity = 10
break
}
switch-case(即時関数)
const quantity = ((item: ItemType): number => {
switch (item) {
case items.apples:
return 10
}
})(items.apple)
dynamic dispatch
type GetQuantityActions = {
[key in itemType]: () => number
}
const getQuantityActions: GetQuantityActions = {
apples: () => 10,
bananas: () => 8,
cherries: () => 6,
}
const quantity = getQuantityActions[item] ? getQuantityActions[item]() : 0