'JSON type object only has parse and stringify methods, but I want to access the objects data
I have a project with NestJS, Typescript and Typeorm. I'm working with the following class Entity
class Event {
user: string,
createdAt: Date,
type: string,
data: JSON
}
In one of my methods I'm making a query to get some events, but I want to access just a few properties of the data attribute because the object has a lot information I don't really need. The problem is that when I try to access the json, for example: receivedEvent.data.myProperty typescript tells me that this property is not available in type JSON. The only solution I can think of is changing the type of the data attribute to a string and parse it to json after the query, but I want to know if there is any other solution to this. This is the code I'm using to query the events:
async getLogs(loanId: string): Promise<Event[]> {
const events = await this.eventRepository.find({
select: ['createdAt', 'user', 'type', 'data'],
where: {
type: In([
'early_payoff',
]),
data: Raw(
/* istanbul ignore next */
() => 'data->"$.GUID" = :id',
{ id: loanId },
),
},
order: {
id: 'DESC',
},
});
console.log(events);
return events.map(e=>{
/// This is where my problem is
const json: any = {"withdrawReason": e.data.withdrawReason}
return {...e, data: json}
});
}
Solution 1:[1]
I found a quick to solution to this problem. I set the event.data to another variable with type and after that Typescript doesn't throws error.
return events.map(e=>{
/// This is where my problem was
const json: any = e.data
const jsonData: any = {"withdrawReason": json.withdrawReason}
return {...e, data: jsonData}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manuel Duarte |
