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

Share
Published by
codeflare

Recent Posts

CSS Houdini: The Future of Custom Styling in Browsers

Introduction Exploring CSS Houdini is an exciting technology that offers web developers unprecedented control over…

20 hours ago

Understanding Micro-Frontends: The Future of Scalable Web Applications

In modern web development, Understanding Micro-Frontends is essential as scalability, maintainability, and modularity become increasingly…

23 hours ago

JavaScript Function Chaining

Introduction Function chaining is a powerful programming technique in JavaScript that allows multiple methods to…

5 days ago

Ten Essential React Native Tips Every Developer Must Know

Introduction React Native has emerged as one of the leading frameworks for mobile app development,…

5 days ago

The Impact of UX/UI Design on Web Development Success

In today’s digital landscape, a website’s design can make or break its success. User Experience…

5 days ago

An Introduction to WebAssembly: What Developers Need to Know

Web development is an ever-evolving field, with new technologies emerging to push the limits of…

6 days ago