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

AWS Expands Payment Options for Nigerian Customers, Introducing Naira (NGN) for Local Transactions

Amazon Web Services (AWS) continues to enhance its customer experience by offering more flexible payment…

2 days ago

Why JavaScript Remains Dominant in 2025

JavaScript, often hailed as the "language of the web," continues to dominate the programming landscape…

4 days ago

Amazon Moves to Upgrade Alexa with Generative AI Technology

Amazon is accelerating efforts to reinvent Alexa as a generative AI-powered “agent” capable of performing…

4 days ago

Smuggled Starlink Devices Allegedly Used to Bypass India’s Internet Shutdown

SpaceX's satellite-based Starlink, which is currently unlicensed for use in India, is reportedly being utilized…

5 days ago

Why Netflix Dumped React For its Frontend

Netflix, a pioneer in the streaming industry, has always been at the forefront of adopting…

6 days ago

Microsoft Files Lawsuit Against Hacking Group Misusing Azure AI for Malicious Content Generation

Microsoft has announced legal action against a 'foreign-based threat actor group' accused of running a…

1 week ago