I recently faced an issue where I needed to extract from an API object values that used dynamic keys. Here’s how I resolved this issue:
function destructureObj(obj: {[key: string]: string}, key: string) {
return [...Object.values(key)]
}
destructureObj(country, country.languages);
Let’s break down what the function above does:
- The first parameter takes an object with a key of type string and it’s values are of type string.
- The second parameter is a string.
- We use destructuring along with using
Object.values()
in order to return the values of the key that we want in the object.