Recently encountered a challenge at work. Here is an example of a class I have:
class A {
map1: Map<number, number> = new Map();
map2: Map<string, string> = new Map();
// a bunch of other data
age: number = 0;
...
}
The goal is to convert this class to/from a JSON string. The reason for doing this is to create a function that can retrieve data and save it to a local text file.
1.
class A {
map1: Map<number, number> = new Map();
map2: Map<string, string> = new Map();
test: number = 0;
toMyString() {
let context = '';
context = '{'
+ '"map1":' + JSON.stringify([...this.map1.entries()])
+ ', "map2":' + JSON.stringify([...this.map2.entries()])
return context;
}
}
let a = new A();
a.map1.set(1, 1);
a.map1.set(2, 2);
a.map2.set('1', '1');
a.map2.set('2', '2');
let b = a.toMyString();
console.log('b: ', b);
let c = JSON.parse(b) as A;
console.log('c: ', c);
c.map1 = new Map(c.map1);
c.map2 = new Map(c.map2);
console.log(c.toMyString()); // c.toMyString is not a function
class A {
map1: Map<number, number> = new Map();
map2: Map<string, string> = new Map();
test: number = 0;
toMyString() {
let context: string[] = [];
context.push('{"test":' + JSON.stringify(this.test) + '}');
context.push(JSON.stringify([...this.map1.entries()]));
context.push(JSON.stringify([...this.map2.entries()]));
return JSON.stringify(context);
}
}
let a = new A();
a.map1.set(1, 1);
a.map1.set(2, 2);
a.map2.set('1', '1');
a.map2.set('2', '2');
let b = a.toMyString();
console.log('b: ', b);
let data: string[] = JSON.parse(b);
console.log('data: ', data);
let c: A = JSON.parse(data[0]) as A;
console.log('c: ', c);
c.map1 = new Map(JSON.parse(data[1]));
c.map2 = new Map(JSON.parse(data[2]));
console.log('c: ', c.test);
console.log('c: ', c);
c.map1 = new Map(c.map1);
c.map2 = new Map(c.map2);
let e = c.toMyString() // c.toMyString is not a function
console.log(e);
- Describe all properties of A, which is quite complex due to the number of properties.