Reputation: 29
My question is somewhat similar to this
I have a map with the key as objectType1 and value as objectType1 | null.
type ObjectType1 = { key:string , value:string }
const newMap = new Map<ObjectType1, Array<ObjectType1>|null>([
[{key:'key1', value:'value1'},null],
]);
what I want to do here is that I want a new object which looks something like:
const newObject = {
key1 : {key: 'key1', value:'value1'}
}
So basically the new object should be able to reference to the object. If i do newObject.key1, i should be able to get the object {key: 'key1', value:'value1'}
How do I go about this?
Upvotes: 1
Views: 158
Reputation: 328252
There are multiple ways to iterate over the Map
's keys and collect them into an object. Here's one:
const newObject =
Array.from(newMap.keys()).
reduce<Record<string, ObjectType1 | undefined>>(
(acc, k) => ({ ...acc, [k.key]: k }), {}
);
// const newObject: Record<string, ObjectType1 | undefined>
Here we are using the keys()
method of Map
to get an iterable iterator of all the key objects. This is not an array, and since we're going to use the reduce()
method of Array
to process it, we first need to convert it into an array via the Array.from()
method.
So Array.from(newMap.keys())
is now an array of the keys, and we use reduce()
to collate these into an object. We do this by starting with the empty object {}
, and, for each element k
in the key array, we spread the previous object into a new object, and add a new property with key k.key
and value k
.
Note that the type of newObject
is Record<string, ObjectType1 | undefined>
, using the Record<K, V>
utility type. It has a string index signature; that means the TypeScript compiler has no idea what the keys of newObject
will actually be. Only that, for every key in newObject
, the property value will be of type ObjectType1 | undefined
. (That undefined
possibility is just there so that if you write newObject.someKeyThatDoesNotActuallyExist
the compiler won't falsely claim that there's a property there of type ObjectType1
. You have to handle possible undefined
/missing properties).
Okay, let's test it out:
console.log(newObject.key1)
// { "key": "key1", "value": "value1" }
Looks good!
Upvotes: 2