skip to Main Content

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


  1.  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.

    Login or Signup to reply.
  2. 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:

    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);
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search