How To Create Objects With Dynamic Keys In TypeScript/JavaScript

I recently wanted to programmatically create several objects with dynamic keys inside another object (basically an object of objects) when working with TypeScript. Using the example below, I will show how I went about it:

Suppose we want to create objects with two properties: id and the url. I create a function which will take a string array of the urls and then loop over the array and create the objects one by one. Since I want to return all the newly created objects inside another object, I will then use the spread operator.

function createObjectsWithDynamicKeys(urls: string[]) {
    let objectKeyPrefix = "myObj_";
    let newObj;

    for (let i = 0; i < urls.length; i++) {
        newObj = {
            [`${objectKeyPrefix}${i}`]: {
                id: i,
                url: urls[i],
            },
            ...newObj
        }
        
 
    }
    
    return newObj;
 }

const urls: string[] = ["https://www.google.com", "https://www.bing.com", "https://www.yahoo.com"];

const result = createObjectsWithDynamicKeys(urls);

console.log(result); 
/*{
*  myObj_0: {
*    id: 0,
*    url: "https://www.google.com"
*  },
*  myObj_1: {
*    id: 1,
*    url: "https://www.bing.com"
*  },
*  myObj_2: {
*    id: 2,
*    url: "https://www.yahoo.com"
*  }
 }*/

This blog post was originally published on my blog Communicode, where I write about different tech topics.

JavaScriptTypeScript
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.