Skip to content

Instantly share code, notes, and snippets.

@ifyour
Created September 20, 2023 23:37
Show Gist options
  • Save ifyour/e5aa7e314b72832841afe394559a6c6a to your computer and use it in GitHub Desktop.
Save ifyour/e5aa7e314b72832841afe394559a6c6a to your computer and use it in GitHub Desktop.
function fromRecords<T>(items: T[], key: keyof T, value: keyof T) {
return Object.fromEntries(items.map(({ [key]: k, [value]: v }) => [k, v]))
}
const users = [
{ id: 'id1', name: 'Alice', email: '[email protected]' },
{ id: 'id2', name: 'Bob', email: '[email protected]' },
]
const userMap = fromRecords(users, 'id', 'name')
console.log(userMap)
// log:
// {
// id1: "Alice",
// id2: "Bob"
// }
@ifyour
Copy link
Author

ifyour commented Sep 20, 2023

将数组转换为一个对象,可以使用键直接查找元素,而不需要遍历数组。这种查找方式的时间复杂度是 O(1),即无论数组有多大,查找时间都是常数。如果需要多次查找,或者数组很大,fromRecords 这种转成对象的方式比 [].find 方法更高效。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment