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.

Author

Recent Posts

Hackers Exploiting Microsoft Teams to Remotely Access Users’ Systems

Hackers are exploiting Microsoft Teams to deceive users into installing remote access tools, granting attackers…

1 day ago

Ethical Hacking Essentials

Data plays an essential role in our lives.  We each consume and produce huge amounts…

2 days ago

Thomas E. Kurtz, co-creator of the BASIC programming language, passes away at 96.

Thomas E. Kurtz, co-creator of the BASIC programming language, passed away on November 12, 2024,…

2 days ago

Mark Cuban believes AI will have minimal impact on jobs that demand critical thinking.

Mark Cuban recently expressed his views on the impact of artificial intelligence (AI) on the…

3 days ago

Free AI training data, courtesy of Harvard, OpenAI, and Microsoft

Harvard researchers have developed a new AI training dataset, the Harvard OpenAI-Microsoft Dataset, aimed at…

5 days ago

Apple Finalizes its AI Toolset With iOS 18.2

Apple's iOS 18.2 Update Introduces Powerful AI Features, Including Genmoji and Image Playground Apple’s latest…

6 days ago