英文:
One additional class in a class - JS
问题
// 这是一个来自项目API的类
[
{
"id": 1,
"categoryId": 1,
"userId": 1,
"category": {
"id": 1,
"name": "Objets"
}
}
]
// 我想在JS中重新创建这个类,以便以上述格式将新信息推送到数组中。
// 在网上进行了一些研究后,我找到了这种解决方案:
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;
}
}
}
}
// 但我不知道如何使用我的第一个构造函数(如下):
// 我有这样的东西:
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 have this class from an API for a project
[
{
"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):
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)
);
Thanks for your help.
答案1
得分: 3
从我理解的情况来看,您有一个ES6类,并尝试使用一些JSON数据进行实例化。鉴于您的JSON数据是作为数组提供的,我会假设您希望最终得到多个classPicture
的实例,每个实例对应JSON数组中的一个项。类似于以下示例:
// 如果它以字符串形式从您的API返回,您可以使用JSON.parse()进行解析。
const data = [
{
"id": 1,
"categoryId": 1,
"userId": 1,
"category": {
"id": 1,
"name": "Category one"
}
},
{
"id": 2,
"categoryId": 2,
"userId": 2,
"category": {
"id": 2,
"name": "Category two"
}
}
];
作为第一步,我建议将两个类分开,如下所示:
class ClassCategory {
constructor(id, name) {
this.id = id;
this.name = name;
}
// 随机方法。在您的情况下,您可以直接访问名称,但如果您使用ES2022或typescript的公共/私有属性,您需要定义getter和setter方法。
getName() {
return this.name;
}
}
class ClassPicture {
constructor(id, userId, category) {
this.id = id;
this.userId = userId;
// 这里的category实际上是您事先创建的类别对象。
this.category = category;
}
// 再次是一个随机方法,只是演示类方法的工作方式。
getCategoryName() {
return this.category.getName();
}
}
在这里,我删除了categoryId属性,因为您已经在类别的JSON对象中拥有它。
最后,您可以这样实例化这些类:
const pictures = [];
for(const picture of data) {
// 实例化类别,您也可以在下面的行中执行它,如下所示
// const pictureInstance = new ClassPicture(picture.id, picture.userId, new ClassCategory(picture.category.id, picture.category.name));
const category = new ClassCategory(picture.category.id, picture.category.name);
const pictureInstance = new ClassPicture(picture.id, picture.userId, category)
pictures.push(pictureInstance)
}
// 允许您从实例中获取类别名称。
console.log(pictures[0].getCategoryName());
重要的是指出,几乎JavaScript中的所有内容都是对象,您可以简单地使用JSON.parse()
解析数据并访问属性,例如:
console.log(data[0].category.name)
我不知道您的确切用例,但如果您不需要与类一起提供的额外功能(例如以特殊方式更改/获取数据的方法 - 想象一个返回firstName + lastName的函数),那么您可以直接访问数据。
英文:
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 like
// If it comes from your API as a string you can JSON.parse() it.
const data = [
{
"id": 1,
"categoryId": 1,
"userId": 1,
"category": {
"id": 1,
"name": "Category one"
}
},
{
"id": 2,
"categoryId": 2,
"userId": 2,
"category": {
"id": 2,
"name": "Category two"
}
}
];
As a first step I'd propose separating the two classes like so:
class ClassCategory {
constructor(id, name) {
this.id = id;
this.name = name;
}
// Random method. You could just directly access the name in your case, but if you use public/private properties from ES2022 or typescript, you'd need to define getter and setter methods.
getName() {
return this.name;
}
}
class ClassPicture {
constructor(id, userId, category) {
this.id = id;
this.userId = userId;
// Here category is actually the category object you create beforehand.
this.category = category;
}
// Again a random method, just demonstrating how the class methods work.
getCategoryName() {
return this.category.getName();
}
}
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
const pictures = [];
for(const picture of data) {
// Instantiate the category, you can also do it in the line below like
// const pictureInstance = new ClassPicture(picture.id, picture.userId, new ClassCategory(picture.category.id, picture.category.name));
const category = new ClassCategory(picture.category.id, picture.category.name);
const pictureInstance = new ClassPicture(picture.id, picture.userId, category)
pictures.push(pictureInstance)
}
// Allows you to get the category name from the instance.
console.log(pictures[0].getCategoryName());
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 like
console.log(data[0].category.name)
I 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.
答案2
得分: 1
const category = class category {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
在一个变量内声明一个类实际上是不正确的做法。正确的方法是:
class category {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
class classPicture {
constructor(id, categoryId, userId, category) {
this.id = id;
this.categoryId = categoryId;
this.userId = userId;
this.category = category
}
}
const newPictureAdded = new classPicture(
1,
2,
JSON.parse(sessionStorage.getItem("id")),
new category(2, 1)
);
一个类只是一个结构。要实际使用它,需要使用 'new' 关键字创建一个类的实例。
英文:
const category = class category {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
you can't actually declare a class inside a variable.
the correct way to do what you want is:
class category {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
class classPicture {
constructor(id, categoryId, userId, category) {
this.id = id;
this.categoryId = categoryId;
this.userId = userId;
this.category = category
}
}
const newPictureAdded = new classPicture(
1,
2,
JSON.parse(sessionStorage.getItem("id")),
new category(2,1)
);
A class is just a structure. To actually use it, you need to create an instance of the class using the 'new' keyword.
答案3
得分: 1
以下是您要翻译的内容:
您不需要在这里使用类来使用您的数据,可以直接使用它。
但是如果您需要将后端数据作为类的实例使用,您可以这样做:
- 将后端数据获取为JSON
- 使用
JSON.parse
进行解析,并提供第二个参数作为恢复函数 - 在恢复函数内部设置对象的原型
- 结果将以您想要的类的实例形式呈现,具有这些类的所有方法和属性
举个例子:
const json = JSON.stringify([
{
"id": 1,
"categoryId": 1,
"userId": 1,
"category": {
"id": 1,
"name": "Objets"
}
}
]);
// 我们使用 key 属性扩展我们的数据
class Picture {
id
categoryId
userId
category
get key() {
return `${this.id} ${this.categoryId} ${this.userId} ${this.category.key}`;
}
};
class Category {
id
name
get key() {
return `${this.id} ${this.name}`;
}
};
const data = JSON.parse(json, (key, val) => {
if (val.categoryId) { // 一些用于确定图片的代码
Object.setPrototypeOf(val, Picture.prototype);
} else if (key === 'category') { // 一些用于确定类别的代码
Object.setPrototypeOf(val, Category.prototype);
}
return val;
});
const [picture] = data;
// 打印图片的类别的 key:
console.log(picture.category.key);
// 打印图片的 key:
console.log(picture.key);
希望这可以帮助您!
英文:
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:
- get your backend data as JSON
- parse it with
JSON.parse
and provide a reviver function as the second parameter - inside the reviver set prototypes of your objects
- as the result you will get your data presented as instances of classes you want with all methods and properties of those classes
As an example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const json = JSON.stringify([
{
"id": 1,
"categoryId": 1,
"userId": 1,
"category": {
"id": 1,
"name": "Objets"
}
}
]);
// we extend our data with key property
class Picture {
id
categoryId
userId
category
get key() {
return `${this.id} ${this.categoryId} ${this.userId} ${this.category.key}`;
}
};
class Category {
id
name
get key() {
return `${this.id} ${this.name}`;
}
};
const data = JSON.parse(json, (key, val) => {
if (val.categoryId) { // some code to determine a picture
Object.setPrototypeOf(val, Picture.prototype);
} else if (key === 'category') { // some code to determine a category
Object.setPrototypeOf(val, Category.prototype);
}
return val;
});
const [picture] = data;
// print picture's category's key:
console.log(picture.category.key);
// print picture's key:
console.log(picture.key);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论