Array of Typed Objects – Extract Union Type of Values for a Given Key

Array of Typed Objects – Extract Union Type of Values for a Given Key

When working with TypeScript, you may come across a scenario where you have an array of objects with different properties, but you want to extract the union type of values for a specific key. This can be useful when you want to perform operations on a specific property across all objects in the array. In this blog post, we will explore different solutions to extract the union type of values for a given key in an array of typed objects.

Solution 1: Using the `map` and `reduce` methods

One way to extract the union type of values for a given key is by using the map and reduce methods. Here’s how you can do it:

interface MyObject {
  id: number;
  name: string;
  age: number;
}

const myArray: MyObject[] = [
  { id: 1, name: "John", age: 25 },
  { id: 2, name: "Jane", age: 30 },
  { id: 3, name: "Bob", age: 35 },
];

const values: Array = myArray.map((obj) => obj.name).reduce((prev, curr) => prev.concat(curr), []);

console.log(values); // Output: ["John", "Jane", "Bob"]

In this solution, we first use the map method to extract the values of the name property from each object in the array. Then, we use the reduce method to concatenate all the extracted values into a single array.

Solution 2: Using the `flatMap` method

Another approach is to use the flatMap method, which combines the steps of mapping and flattening the resulting array. Here’s an example:

const values: Array = myArray.flatMap((obj) => obj.name);

console.log(values); // Output: ["John", "Jane", "Bob"]

In this solution, we directly use the flatMap method to extract the values of the name property from each object in the array. The resulting array is automatically flattened, giving us the desired union type of values.

Solution 3: Using a custom function

If you prefer a more customizable approach, you can create a custom function to extract the union type of values for a given key. Here’s an example:

function extractValues(array: T[], key: K): Array {
  return array.map((obj) => obj[key]);
}

const values: Array = extractValues(myArray, "name");

console.log(values); // Output: ["John", "Jane", "Bob"]

In this solution, we define a generic function extractValues that takes an array of objects and a key as arguments. The function uses the map method to extract the values of the specified key from each object in the array.

These are three different solutions to extract the union type of values for a given key in an array of typed objects. Choose the one that best suits your needs and integrate it into your TypeScript code.

Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *