0

I got a function which should save multiple JSON Objects into an Array of the Type "Contact"

getContacts(){
    let self = this;
    $.ajax({
        type: "GET",
        url: "/chat/contacts/",
        dataType:"json",
        success: function(response){
            let obj = response;
            let i = 1;
            let contacts: Contact[] = [];
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    let val = obj[key];
                    contacts[i].id = val["id"]; //<-- contacts[i] is undefinded
                    contacts[i].partner = val["partnerId"];
                    contacts[i].name = val["name"];
                    contacts[i].type = val["type"];
                    console.log(contacts[i]);
                }
            }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(errorThrown);
        }
    });
}

At the marked point it says

contacts[i] is undefinded

How do i have to initialize the Array to make it working?

Here is the Contact Class:

class Contact extends BaseModel{
    static CCO_ID = "id";
    static CCO_PARTNER = "partner";
    static CCO_NAME = "name";
    static CCO_TYPE = "type";


    partner: Number;
    name: String;
    type: Number;
}
1
  • use contacts.push Commented Aug 31, 2017 at 6:57

1 Answer 1

3

You need first to define that contacts[i] is an object and then use it's properties.

And one more thing, you are starting from index 1, in Javascript array's index is starting from 0. Be aware if that is not intentionally.

let val = obj[key];
contacts[i] = new Contact(); // <-- Look here
contacts[i].id = val["id"];
contacts[i].partner = val["partnerId"];
contacts[i].name = val["name"];
contacts[i].type = val["type"];
console.log(contacts[i]);
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.