0

I have a Typescript object that will look like this:

{
    "obj1" : { object: type1;};
    "obj2" : { object: type2;};
    "obj3" : { object: type3;};
    "obj4" : { object: type4;};
    "obj5" : { object: type5;};
}

I want to map it to

{
    "obj1" : type1;
    "obj2" : type2;
    "obj3" : type3;
    "obj4" : type4;
    "obj5" : type5;
}

My concern is preserving types here.

I am using typescript 3.7.2 let me know even if there is a solution in a later version.

Can anyone help ?

UPDATE ---- My problem is typing not object mapping. I want the types of my objects to be reflected in compile time.

kerolos
  • 127
  • 1
  • 2
  • 10
  • Does this answer your question? [map function for objects (instead of arrays)](https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays) – bugs Sep 28 '20 at 09:17
  • My problem is typing not object mapping. I want the types of my objects to be reflected in compile time. – kerolos Sep 28 '20 at 10:36

2 Answers2

3

Like this?

interface Foo {
  obj1: { object: string };
  obj2: { object: number };
  obj3: { object: boolean };
}

type FooMapped = { [key in keyof Foo]: Foo[key]["object"] };

const foom: FooMapped = {
  obj1: "obj1",
  obj2: 432,
  obj3: true
}

And a more generic solution:

function mapObject<R extends Record<string, { object: unknown }>>(record: R) {
  let ret: any = {};
  Object.keys(record).forEach((key) => {
    ret[key] = record[key]["object"];
  });

  return ret as {
    [key in keyof R]: R[key]["object"];
  };
}

const foo = mapObject({
  bar: { object: 412 },
  baz: { object: true }
});

console.log(foo);
  • Thank you, I could not use it in a generic way, But It did the deed. Generic meaning make a function that do the mapping and the typing for the input object. – kerolos Sep 28 '20 at 10:53
  • I added a generic function – ThatAnnoyingDude Sep 28 '20 at 11:27
  • I have another question if you would be so kind to have a look https://stackoverflow.com/questions/64101854/typescript-i-want-a-type-which-is-the-union-of-all-types-in-an-abject-properties – kerolos Sep 28 '20 at 12:05
  • I have yet another question https://stackoverflow.com/questions/64121881/using-a-type-as-a-parameter-typescript I am really questioning if it is possible. Have a look if you would. Thank you a lot. – kerolos Sep 29 '20 at 14:38
0

Please take a look this code:

let objects = {
    "obj1" : { "object": "type1"},
    "obj2" : { "object": "type2"},
    "obj3" : { "object": "type3"},
    "obj4" : { "object": "type4"},
    "obj5" : { "object": "type5"},
};
for (let key of Object.keys(objects)) {
  objects[key] = objects[key]['object'];
}
console.log(objects);