fromPairs
arrays
Returns an object composed from key-value pairs.
Installation
Import
import { fromPairs } from '@tulx/utils';Source Code
Implementation
/**
* Returns an object composed from key-value pairs.
*
* @param pairs - The key-value pairs.
* @returns The new object.
*
* @example
* ```ts
* fromPairs([['a', 1], ['b', 2]]); // { 'a': 1, 'b': 2 }
* ```
*/
export function fromPairs<T>(
pairs: readonly [string | number, T][]
): Record<string, T> {
const result: Record<string, T> = {};
const len = pairs.length;
for (let i = 0; i < len; i++) {
const pair = pairs[i];
const key = pair[0];
// Optimize: avoid String() call for string keys
if (typeof key === 'string') {
result[key] = pair[1];
} else {
result[String(key)] = pair[1];
}
}
return result;
}
Example
import { fromPairs } from '@tulx/utils';
fromPairs([['a', 1], ['b', 2]]); // { 'a': 1, 'b': 2 }Related Functions
chunk
Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.
compact
Creates an array with all falsy values removed. The values false, null, 0, "", undefined, and NaN are falsy.
concat
Creates a new array concatenating array with any additional arrays and/or values.
difference
Creates an array of array values not included in the other given arrays. The order and references of result values are determined by the first array.
differenceBy
This method is like difference except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which they're compared.
differenceWith
This method is like difference except that it accepts comparator which is invoked to compare elements of array to values.