Daniel Stephens
Daniel Stephens

Reputation: 3249

Convert an object to a key/value object in TypeScript

I am new to TypeScript and I have the given object:

let obj = {hash: 'foo', filename: 'bar', blob_size: 'bas'};

And I would like to convert it into the following

{'foo': ['bar', 'bas']}

This was my first attempt:

[...obj.values()].map((v) => {v.hash: [v.filename, v.blob_size]}]

But that seems to be invalid in TS. In other languages I would have called it simply Array and Dictionary or Map. Could someone give me a hint how to convert the first to the second example? And also, what would be the corresponding type names? In both cases typeof just returns Object.

Upvotes: 0

Views: 248

Answers (1)

Son Nguyen
Son Nguyen

Reputation: 1482

TypeScript shape of your destination object could be defined as:

type HashObj = {
  [hash: string]: string[]
}

Basically an object with key of string and value of string array

You can convert to it this way:

let obj = { hash: 'foo', filename: 'bar', blob_size: 'bas' };
const result: HashObj = { [obj.hash]: [obj.filename, obj.blob_size] };

Upvotes: 1

Related Questions