Marco Roy
Marco Roy

Reputation: 5285

How to instantiate an array with key-value pairs in TypeScript?

I want to instantiate an array of key-value pairs in one step, but I can't figure out how. Auto-numbering won't work in my use-case. I can only make it work in two steps:

let army: string[] = []; army[100] = 'centuria'; army[1000] = 'legion'; ...

What I'd like to be able to do, which is available in most other programming languages:

let army: string[] = [ 100 => 'centuria', 1000 => 'legion', ... ];

Is there any way to do this in TypeScript?

Edit: I can't use an object as I need to pass the data to an interface which is expecting an array.

Upvotes: 1

Views: 19910

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164257

There's no such functionality in javascript, but you can easily create it:

function arrayFactory<T>(obj: { [key: number]: T }): T[] {
    let arr = [];

    Object.keys(obj).forEach(key => {
        arr[parseInt(key)] = obj[key];
    });

    return arr;
}

let arr = arrayFactory({ 100: "centuria", 1000: "legion" });
console.log(arr); // [100: "centuria", 1000: "legion"]

(code in playground)

The question is why not using an object as key/map to store this data? What different does it make to use an array (which is basically an object itself)?

Upvotes: 6

Related Questions