DEV Community

adro.codes
adro.codes

Posted on

Extract key values into an array

Use case

You have an array of objects and want to pull out all the values related to the amount into an array.

What will happen

We will be creating a Higher-order function that can be used with the reduce method. The method will then loop through the items in an array and pull out all the values for a specific key.

Data structure

I am providing a Vanilla JS and Typescript example, the interface can be ignored if you are using vanilla JS

interface Data {
  id: string
  amount: number
}

const arr: Data[] = [
  { id: "a-a-a-a", amount: 5 },
  { id: "b-b-b-b", amount: 50 },
]
Enter fullscreen mode Exit fullscreen mode

Method - Vanilla JS

export function getKeyValues(key) {
  return (acc, cur) => acc.concat(cur[key])
}
Enter fullscreen mode Exit fullscreen mode

Usage

const amounts = arr.reduce(getKeyValues("amount"), [])
// -> [5, 50]

// Because the method is a HOF, we can create separate methods to use later
const getAmounts = getKeyValues("amount")
const getIds = getKeyValues("id")

const amounts = arr.reduce(getAmounts, [])
// -> [5, 50]

const ids = arr.reduce(getIds, [])
// -> ["a-a-a-a", "b-b-b-b"]
Enter fullscreen mode Exit fullscreen mode

Method - Typescript

// Type definition for a `.reduce` method
type ReducerHOF<A = any[], C = any> = (
    accumulator: A,
    current: C,
    index: number
) => A

/**
 * Extracts the values for a specific key
 *
 * @export
 * @template T
 * @template K
 * @param {K} k
 * @returns {ReducerHOF<T[K][], T>}
 */
export function getKeyValues<T, K extends keyof T>(k: K): ReducerHOF<T[K][], T> {
    return (acc, cur): T[K][] => acc.concat(cur[k])
}

/*
For our example;
T = Data
K = "id" | "amount"
Return type, if K == "id" -> string[]
Return type, if K == "amount" -> number[]
*/
Enter fullscreen mode Exit fullscreen mode

Here we use Generics to add type safety to the method. For example, with vanilla JS you'll be able to get the values for the key comments. Which will return an array of undefined values; not ideal. Of course, you can expand the method to check if a key exists; it will also provide you with autocomplete options within your IDE.

Usage

const amounts = arr.reduce(getKeyValues("amount"), [])
// -> [5, 50]
Enter fullscreen mode Exit fullscreen mode

Takeaways

This method allows you to pull out the values of any key in an array of objects. Using Higher-order functions allows you to encapsulate functionality to make more maintainable and readable code.


Thank you for reading my article, it really means a lot! ❤️ Please provide any feedback or comments, I'm always looking to improve and have meaningful discussions.

👋 until next time!

Top comments (0)