Transform 2-D String Array to Object Using TypeScript and JavaScript

Sometimes you need to convert a 2-dimension array of strings into an object. Perhaps you received data from the server and need to populate your objects. Or perhaps you have data to send to the server and need to convert an array to an object parameter for the REST call.

The below code is a quick utility for doing this conversion. However, there are a couple of interesting TypeScript lines.

export const twoDimArrayToObject = function(array: string[][]) {
    const returnObject: {
        [key: string]: string
    } = {};
    array.forEach((element) => {
        returnObject[element[0]] = element[1];
    })
    return returnObject;
}

First, take a look at the typing of returnObject. In plain English, the return type is an object that can have zero-to-many properties. The properties must have an index signature of type ‘string’ and each property must have one value of type ‘string’.

Another way of saying this is that when returnObject is indexed with a certain string, it will return a string. Take a look at this page of the TypeScript docs for more reading.

Another interesting feature of this code is the typing of the parameter passed to twoDimArrayToObject. array: string[][] might not be the intuitive way to type a two dimensional array that could container a value such as the below:
[ ['state', 'Texas'], ['city', 'Fort Worth'] ]

When I first started with TypeScript I tried to type this as [string, string][] because it seemed more visually intuitive. [string, string] is actually defining a tuple, so in theory there’s nothing wrong with this (depending on the data passed in), but it’s less commonly used for a 2-d array than string[][].

I hope this utility proves useful for you.

Link to the gist on github:

https://gist.github.com/Jon20111/e84e8767c409085be9d837199292cfc2

Share this post:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.