Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active March 15, 2023 04:37
Show Gist options
  • Save yano3nora/17e0e59858b10099ceb66e88c066a784 to your computer and use it in GitHub Desktop.
Save yano3nora/17e0e59858b10099ceb66e88c066a784 to your computer and use it in GitHub Desktop.
[js: object / keys - Object.fromEntries] Create Object by Arrays. #js
/**
* type inferable Object.keys
*
* NOTE key が number な型定義だと number[] になりつつ
* 「 js の object key は全て string 」という仕様で
* string[] になるので、後続で map(Number) など必要
*/
export const objectKeys = <T extends object>(target: T): (keyof T)[] => (
Object.keys(target).map(key => key as keyof T)
)
/**
* objectByKeys との組み合わせで json の keys を
* string union で型定義しつつバラしたり
*/
import { issues as issuesData } from 'data.json' // 何らか固定データ
export type Issue = {
key: keyof typeof issuesData
subject: string
}
export const issues: Record<Issue['key'], Issue> = (
objectByKeys(objectKeys(issuesData), key => ({
key,
subject: issuesData[key].subject.trim(), // 整形してシステム取り込み的な
}))
)
console.log(
issues['型推論可能なキー'].subject
)
/**
* @example
* objectByKeys([1, 2, 3])
* //=> { '1': undefined, '2': undefined, '3': undefined }
*
* objectByKeys([1, 2, 3], 'initial')
* // => { '1': 'initial', '2': 'initial', '3': 'initial' }
*
* objectByKeys([1, 2, 3], key => Number(key))
* // => { '1': 1, '2': 2, '3': 3 }
*
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
* @link https://zenn.dev/yano3nora/articles/cb00fad3b445c0
*/
export const objectByKeys = <T extends string|number|symbol, U = undefined>(
keys: T[],
initial?: U | ((key: T) => U),
): Record<T, U> => Object.fromEntries([
...keys.map(key => [
key,
initial instanceof Function ? initial(key) : initial,
])
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment