I have this class from an API
[
{
"id": 1,
"categoryId": 1,
"userId": 1,
"category": {
"id": 1,
"name": "Objets"
}
}
]
I would to re-create this class in JS to push new informations in an array with the above format.
With few research on internet I find this kind of solution :
export class classPicture {
constructor(id, categoryId, userId, category) {
this.id = id;
this.categoryId = categoryId;
this.userId = userId;
const category = class category {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
}
}
But I don’t know how to use my first constructor (bellow):
constructor(id, categoryId, userId, category)
I have things like that :
export class classPicture {
constructor(id, categoryId, userId, category) {
this.id = id;
this.categoryId = categoryId;
this.userId = userId;
const category = class category {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
}
}
const newPictureAdded = new classPicture(
1,
2,
JSON.parse(sessionStorage.getItem("id"));
category(2,1)
);
I also tried few other things but which where not really smart (this is not smart but…)
Of course, I first looked on internet, but i didn’t or I didn’t what to look for.
Thanks for your help.
3
Answers
you can’t actually declare a class inside a variable.
the correct way to do what you want is:
A class is just a structure. To actually use it, you need to create an instance of the class using the ‘new’ keyword.
You don’t need a class here to use your data, use it as it is.
BUT if you need your backend data as instances of a class you could do this:
JSON.parse
and provide a reviver function as the second parameterAs an example:
From what I understand, you have an ES6 class and are trying to instantiate it with some JSON data. Given that your JSON data comes in as an array, I’d asusme you’d want to end up with multiple instances of
classPicture
for each item in the JSON array. Something likeAs a first step I’d propose separating the two classes like so:
Here I’m dropping the categoryId property, since you already have that in your category JSON object.
Finally, you can instantiate the classes like so
It’s important to point out that almost everything in javascript is an object and you could simply
JSON.parse()
your data and access the properties likeI don’t know your exact use case, but if you don’t need the extra functionality that comes with classes (e.g. methods that change/get your data in a special way – think a function that gives you back firstName + lastName) you can just access your data directly.