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.

2
  • Does this answer your question? map function for objects (instead of arrays) Commented Sep 28, 2020 at 9:17
  • My problem is typing not object mapping. I want the types of my objects to be reflected in compile time. Commented Sep 28, 2020 at 10:36

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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.
I added a generic function
I have another question if you would be so kind to have a look stackoverflow.com/questions/64101854/…
I have yet another question stackoverflow.com/questions/64121881/… I am really questioning if it is possible. Have a look if you would. Thank you a lot.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.