Array/Since
1.38.0keyBy
Converts an array of objects into an object keyed by the value of a specified property.
keyBy(array, key):Record<string, T>Parameters
arrayT[]requiredThe array of objects to convert into a keyed object.
keyKrequiredThe property key whose value is used as the key in the resulting object.
Returns
Record<string, T>An object where each key is created from the specified property value and maps to the corresponding array element.
Examples
01
Basic usage
Create an object keyed by the id property of each item.
TypeScript
import { keyBy } from "@cyref/js";
const users = [
{ id: "1", name: "Amir" },
{ id: "2", name: "Sara" },
{ id: "3", name: "Reza" },
];
const result = keyBy(users, "id");
console.log(result);
// {
// "1": { id: "1", name: "Amir" },
// "2": { id: "2", name: "Sara" },
// "3": { id: "3", name: "Reza" },
// }02
Using another property
The key can be any property available on the object type.
TypeScript
import { keyBy } from "@cyref/js";
const products = [
{ sku: "LP-01", name: "Laptop" },
{ sku: "PH-01", name: "Phone" },
{ sku: "TB-01", name: "Tablet" },
];
const result = keyBy(products, "sku");
console.log(result);
// {
// "LP-01": { sku: "LP-01", name: "Laptop" },
// "PH-01": { sku: "PH-01", name: "Phone" },
// "TB-01": { sku: "TB-01", name: "Tablet" },
// }03
Duplicate keys
If multiple elements have the same key value, the later element replaces the previous element.
TypeScript
import { keyBy } from "@cyref/js";
const users = [
{ id: "1", name: "Amir" },
{ id: "2", name: "Sara" },
{ id: "1", name: "Reza" },
];
const result = keyBy(users, "id");
console.log(result);
// {
// "1": { id: "1", name: "Reza" },
// "2": { id: "2", name: "Sara" },
// }04
Empty array
An empty array produces an empty object.
TypeScript
import { keyBy } from "@cyref/js";
const result = keyBy([], "id");
console.log(result);
// {}Built with@cyref/js·Official documentation