Reputation: 255
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;
}
Upvotes: 0
Views: 11851
Reputation: 68655
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]);
Upvotes: 3