javascript

Convert Array to Object in TypeScript

TypeScript is a superset of JavaScript that adds static typing to the language. Developed by Microsoft, it allows developers to define variable types, function signatures, and object shapes, which can help catch errors at compile time rather than at runtime. This feature enhances code quality and maintainability, making it easier to understand and refactor large codebases.

In this article, we are going to convert two (2) arrays to objects using TypeScript. The first thing we will do is to define the arrays.

Let’s have two (2) arrays:

let a = ["coke", "fanta", "sprite", "viju"]
let b = [1, 2, 44, 55]

Next, we will write a function that converts the array to objects:

const convertToObj = (a:any, b:any) => {
    if (a.length != b.length ||
        a.length == 0 ||
        b.length == 0) {
        return null;
    }

    // Using reduce() method
    let object = a.reduce((acc:any, element:any, index:any) => {
        return {
            ...acc,
            [element]: b[index],
        };
    }, {});

    return object;
  }

  console.log(convertToObj(a,b))

Here’s our result on the console:

This is how to convert arrays to objects in Typescript.

We can also do the same for JavaScript as follows:

let a = ["coke", "fanta", "sprite", "viju"]
 let b = [1, 2, 44, 55]

 const convertToObj = (a, b) => {
    if (a.length != b.length ||
        a.length == 0 ||
        b.length == 0) {
        return null;
    }

    // Using reduce() method
    let object = a.reduce((acc, element, index) => {
        return {
            ...acc,
            [element]: b[index],
        };
    }, {});

    return object;
  }

  console.log(convertToObj(a,b))

We should get the same result.

Recent Posts

Common Pitfalls in React Native Development

Now that React Native is your go-to framework for building cross-platform mobile applications efficiently, it's…

2 days ago

Search Through An Array of Objects to Find a Particular Value

When dealing with complex data structures. For example, you might have an array of user…

6 days ago

What are WebSockets?

If you've played Fortnite, watched a live ESPN match, or used Slack or Microsoft Teams,…

2 weeks ago

How to Use Custom Hooks in React

A custom hook in React is a JavaScript function that leverages React’s built-in hooks—like useState,…

2 weeks ago

South Korea bans downloads of DeepSeek AI until further notice

The South Korean government announced on Monday that it had temporarily halted new downloads of…

3 weeks ago

Which programming language is best for software development?

As a software developer, choosing the right programming language for software development can be a…

3 weeks ago