I am having problems adding a property and value to an object based on a value in a for loop. Here's my code.
"use strict";
var chirper = {};
chirper.tweetsArray = [];
chirper.tweets = [];
chirper.friends = [];
chirper.friendsByName = [];
chirper.masterAjax = function (url, method, success, error, data) {
var request = new XMLHttpRequest();
request.open(method, url);
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
if (success && typeof (success) == 'function') {
success(this.response, this.status);
}
}
else {
if (error && typeof (error) == 'function') {
error(this.response, this.status)
}
}
};
request.onerror = function () {
if (error && typeof (error) == 'function') {
error(this.response, this.status);
}
};
if (data) {
request.send(JSON.stringify(data));
}
else {
request.send();
}
};
This is a function that I use over and over depending on where I need to get or post info to.
chirper.getAllFriends = function () {
chirper.masterAjax('https://example-name.example.com/ccchirper/friends/.json', 'GET', function (response) {
var data = JSON.parse(response); for (var i in data) { chirper.friends.push(data[i]); chirper.friendsByName.push(data[i].userName)};
}, function (response, status) {
alert('Status: ' + status + '. Error message: ' + response);
});
};
chirper.getAllTweets = function () {
for (var i in chirper.friendsByName){
chirper.masterAjax('https://' + chirper.friendsByName[i] + '.example.com/ccchirper/tweets/.json',
'GET',
function (response) {
var data = JSON.parse(response);
for (var j in data) { data[j].name = chirper.friendsByName[i]; chirper.tweetsArray.push(data[j]);
};
},
function (response, status) {
alert('Status: ' + status + '. Error message: ' + response);
});
};
}
I have been calling these functions from the console to test them.
I first call chirper.getAllFriends()
to populate chirper.friendsByName
. An example of what it returns would be ['andy','bob','john','tom']
After it returns I call chirper.getAllTweets()
to populate chirper.tweetsArray
Then I call chirper.tweetsArray
and it returns an array of objects [obj,obj,obj]
each of these objects is
obj
text: "blah blah blah'
image: "url.goes.here.com"
time: 124223534346
name: tom
each object has the correct properties and values but the name property always get the value of the last name in the chirper.friendsByName
array.
What I want to have happen is all objects from 'andy' should get the name 'andy', all the ones from 'bob' should get the name 'bob' etc.