Created
September 20, 2023 23:37
-
-
Save ifyour/e5aa7e314b72832841afe394559a6c6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
将数组转换为一个对象,可以使用键直接查找元素,而不需要遍历数组。这种查找方式的时间复杂度是 O(1),即无论数组有多大,查找时间都是常数。如果需要多次查找,或者数组很大,
fromRecords
这种转成对象的方式比[].find
方法更高效。