2

How to create/save an array of JSON objects only when there is a new item? The problem I am having is:

  1. How can I create/save JSON objects directly or do I have to have a corresponding class object created?
  2. What Is the best way to check if particular item exists or not?
4
  • Your question is not clear as-is. Perhaps you could show us some code to better illustrate the question here? Commented Jan 29, 2016 at 17:01
  • You don't really need to do anything special, just use any: jsfiddle.net/ywp4n8dy/1 Commented Jan 29, 2016 at 17:04
  • sharing a js example of what you want to create might help. :) Commented Jan 29, 2016 at 19:07
  • @Corey Ogburn. This works for me. can we do the same with loadash? Commented Feb 1, 2016 at 2:21

1 Answer 1

1

You can store the json in variables of class any but usually you will want to have some typing on these object so what I usually do is having a fromJson static method on my model classes that will instantiate an object from a json like that:

class User {

    public firstname: string;
    public lastname: string;
    public age: number;

    constructor() {
    }

    public static fromJson(userJson: any): User {
        var user = new User();

        this.firstname = userJson.firstname;
        this.lastname = userJson.lastname;
        this.age = userJson.age;

        return user;
    }
}

If one of your properties is a class you can also have a from json on it and embed it in the from json like that:

class User {

    public firstname: string;
    public lastname: string;
    public status: Status;

    constructor() {
    }

    public static fromJson(userJson: any): User {
        var user = new User();

        this.firstname = userJson.firstname;
        this.lastname = userJson.lastname;
        this.status = Status.fromJson(userJson.status);

        return user;
    }
}

Hope it helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.