# How To Merge Two Array of String Into A Key/Value Map (Object) In JavaScript

There are different ways to merge two arrays in JavaScript. You can use one of the following:

1. using the spread operator e.g. `[ ...array1, ...array2]`
    
2. using [Array.prototype.concat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)
    
3. using [Array.prototype.push()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)
    

None of those will help if you need to merge two arrays to a Map or key/value pair for specific use. Given the example form below, we want to convert the separate array of keys and values, into an object.

![Web form to collect environment variable](https://cdn.hashnode.com/res/hashnode/image/upload/v1686243334059/8787c0be-ce7f-4e5f-93e1-308a5cba8a7d.png align="center")

How do we merge the form data to give us an object like what you see below?

```json
{
  "DB_URL": "example.com",
  "NODE_ENV": "production"
}
```

## Solution

We're going to create a function that takes in two arguments: one for the array of keys, and the other for the values. That function will use the `reduce()` method to produce an object of key/value pair.

This is how the function will look like:

```typescript
function mergeArraysToMap(keys: string[], values: string[]): { [key: string]: string } {
  if (keys.length !== values.length) {
    throw new Error("The number of keys and values must be the same.");
  }

  // Use reduce to create the key/value map
  const mergedMap: { [key: string]: string } = keys.reduce((map, key, index) => {
    map[key] = values[index];
    return map;
  }, {});

  return mergedMap;
}
```

The `mergeArraysToMap` function takes two arrays (`keys` and `values`) as arguments. It checks if the number of keys and values is the same and then uses the `reduce` method to create the key/value map. Then it returns the merged key/value pair.

We can take this further and ensure that we don't accept an empty string for the key or value. For that, we can modify the reduce method as follows:

```typescript
const mergedMap: { [key: string]: string } = keys.reduce(
    (map, key, index) => {
      if ((key && !values[index]) || (!key && values[index]))
        throw new Error("invalid key/pair");

      if (key && values[index]) map[key] = values[index];
      return map;
    },
    {} as Record<string, string>
  );
```

With that implementation, we can be sure that we will get a valid key/value pair.

You can play around with the code on the TypeScript [playground using this link](https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAWwKYCcDmqCC70CGAngM4AqcAsgQA4AUA1qqQFyIlToxiYDaAugBpEANwIAbEKhJsOXHgICUbAN6JeTIrM7dM-bfMyIAvohUAoRIhjBEjZiQB041DygALRAEIAvD9ESUk4ubu6KZpZWiB7ocADuiGCoCQCi+HDodABEZO6oiSDIAEYYiHC2miSIBGAAJgGS0iggHIgl0XnsBGiOWYoA3JHG5pEA9KOIAKok+eiotSAQ+VBwiBBzBFDLnZqjYo0otJEQCK1oWPPUNKrqmga6+uw6PCaI-pWOcwtLdJFWdMhaMJNMJuLVUAAPcI+AB8ESiURsdnsREQADI0d59kFeGDIfxwgAfQl2LyadGY7HSXF1fGKRR-BEdWIJJKpdKZLLcfYweq7GgEGDoPqDRlWJEoikNHF4iEEw40DTMfhvaXU2X8QZMxBzKAgdBIQE0LVRYyCRkqUwEKoAJVQJ3QtQAPHJdMJXTwYZEBiMrLr9YaMNhaldBsNzONECkId0aC5EC0CNhzCcwK1KvcFCr-LwsgARABCAH1JjaADJZYRZAByAHk8ykiylqwA1SuILKaLKalOnKBqmRPQwCVW5yGxlyOE7IdtZGixb6wBCzqnd0Wp1pzEggcRQK6q87YPCEUgUK4okjCKkkH0buCT8RwTB0Lc7ve0AZAA).

> Subscribe 👇🏽 to get notified about new blog posts from me
