0

I have two classes/interfaces:

class ImageObjectsJson {
    [markerId : string] : WktGeometryJson[];
}

class ImageObjects {
    [markerId : string] : ImageObject[]
}

I know the contructor of ImageObject which takes WktGeometryJson object as a parameter. So I can call:

const wkt : WktGeometryJson = {... something useful here ...};
const imageObject : ImageObject = new ImageObject(wkt);

How to create ImageObjects, having ImageObjectsJson, leaving keys unchanged?

forestgril
  • 85
  • 7
  • 1
    Does this answer your question? [map function for objects (instead of arrays)](https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays) – Lesiak Jun 29 '21 at 09:54
  • Thanks, I am not sure... :) In the mentioned answer, they are transforming values to the same type (numbers). I want to cast values to a different type specified by the second interface. I will look again, whether I can return a different type. – forestgril Jun 29 '21 at 10:04
  • Yes, final versions of the Answer post, with ES6 look quite good actually. Thanks! – forestgril Jun 29 '21 at 12:23
  • Also it seems a good - probably a better - answer is here (using lodash): https://stackoverflow.com/questions/19023226/map-over-object-preserving-keys – forestgril Jul 01 '21 at 19:15

1 Answers1

1

Working example - on top of map function for objects (instead of arrays)

interface WktGeometryJson {
  name: string
}

class ImageObject {
  imageName: string;

  constructor(json: WktGeometryJson) {
    this.imageName = json.name;
  }
}

class ImageObjectsJson {
    [markerId : string] : WktGeometryJson[];
}

class ImageObjects {
    [markerId : string] : ImageObject[]
}

const imJson: ImageObjectsJson= {
  aaa: [{name: '1'}, {name: '2'}],
  bbb: [{name: '3'}]
}

const imObj = Object.fromEntries(
  Object.entries(imJson).map(
    ([propName, wktArray]) => [propName, wktArray.map(wkt => new ImageObject(wkt))]
  )
);

console.log(imObj);

Playground link

Lesiak
  • 22,088
  • 2
  • 41
  • 65