In my NodeJS app i get an JSON object within jade (which works fine). Here in i tried to collect(srcTweets) only the relevant data and return this in a new JSON object(stgTweets). Which i use for Dynamic Table use.
Here fore i use the following scrip:
var srcTweets = [];
var srcTweets = !{JSON.stringify(tweets)};
var aantalSrcTweets = srcTweets.length;
//Loop throug all tweets and collect all relevant elementen from srcTweet:
var stgTweet = {}
var stgTweets = [];
console.info('----------START LOOP--------------------');
for(var i = 0; i < aantalSrcTweets; i++){
console.info(i);
stgTweet.Id = srcTweets[i]._id;
stgTweet.userId = srcTweets[i].user.id;
stgTweet.userFollowerCount = srcTweets[i].user.followers_count;
stgTweet.userFriendCount = srcTweets[i].user.friends_count;
stgTweet.userFavouritesCount = srcTweets[i].user.favourites_count;
stgTweet.text = srcTweets[i].text;
stgTweet.coordinates = srcTweets[i].coordinates;
stgTweet.userLocation = srcTweets[i].user.location;
stgTweets[i] = stgTweet;
console.info(stgTweets[i]);
console.info(i);
}
console.info('----------END LOOP--------------------');
//here i get the same items
console.info(stgTweets[0]);
console.info(stgTweets[1]);
When i print different index numbers of the array "stgTweet[0] and stgTweet[1]" the same data is showed. I tried to figure it out by logging the elements in the for loop , but that looks fine. And i realy don't know where to look futher.
How do i fill the array with different objects in stead of the same object, what happens in the script above.
Here is an example of the srcTweets:
[
Object {
_id="56e19eb1ac5e621e0797c423",
truncated=false,
text="#Model_Symphony nu ja,
s... prima Energiequelle...",
more...
},
Object {
_id="56e1a73eac5e621e0797c424",
truncated=false,
text="Vandaag aangekondigd doo...",
more...
},
Object {
_id="56e1a7b4ac5e621e0797c425",
truncated=false,
text="Mooi bedrijfsbezoek aan ...",
more...
}
]
The reason is because you're reusing the same object for every element in the array and objects are assigned by reference in Javascript, so stgTweets[0] === stgTweets[1].
What you could do instead is move your stgTweet declaration inside the loop (or just re-assign the value directly as shown below) so that a new object is created for each array element:
var stgTweets = new Array(aantalSrcTweets);
for (var i = 0; i < aantalSrcTweets; i++){
stgTweets[i] = {
Id: srcTweets[i]._id,
userId: srcTweets[i].user.id,
userFollowerCount: srcTweets[i].user.followers_count,
userFriendCount: srcTweets[i].user.friends_count,
userFavouritesCount: srcTweets[i].user.favourites_count,
text: srcTweets[i].text,
coordinates: srcTweets[i].coordinates,
userLocation: srcTweets[i].user.location
};
}
Related
I'm quite new to JavaScript and programming in general and figured I'd hone my abilities by working on a small project. The idea is that I have a form for information on an event, an input for the name, date, time and a small thumbnail image.
I want each event to be an object inside of an array, so I would have something like:
var concerts = {};
for (var i = 1; i < 11; i++) {
window["concert"+i] = new Object();
}
and the array would end up being something:
var concerts = [concert1, concert2, concert3]
and so on.
How could I get this loop to work so that it would take the 3 parameters and create a new object in the array named 'concert'+i? Thanks for reading!
Concerts must be an array:
var concerts = [];
for (var i = 0; i < 10; i++) {
concerts[i] = {
//maybe also giveit a name if you want to:
name:"concert"+i
};
}
You can access it like this:
concerts[0].name="Wacken";//first concert...
Note that this:
window["concert"+i] = new Object();
is very bad style...
First you declare a variable concerts of type object. But you want an array. That first line makes your code very confusing.
You have to start with an empty array:
var concerts = []; // alternatively: new Array();
In the end you'd like to have a structure like this:
[
{ /* object 1 */ },
{ /* object 2 */ }
]
Now you can run a foor-loop and populate the array:
for (var i = 0; i <= 10; i++) {
concerts.push({['concert' + i]: {}});
}
This will return something like:
[
{'concert0': {}},
{'concert1': {}},
// skipped
{'concert10': {}}
]
Later you can populate the objects. This is however not a very nice style. Maybe you should reconsider if it is really necessary to give a name to every object like concert0...10.
Go rather for:
var concerts = [
{
'name': 'concert0',
'location': 'somewhere'
}
// continue with other objects
];
Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}
So, I have been trying for a while now and no luck. Currently I have an associative array as based on PSN profile data:
var PROFILE = {};
PROFILE.profileData = {};
PROFILE.titles = {};
and is used like this further down in the code:
PROFILE.profileData.onlineId = profileData.onlineId;
PROFILE.profileData.region = profileData.region;
PROFILE.titles[title.npCommunicationId] = title; //For looped, can be many
PROFILE.titles[title.npCommunicationId].trophies = {};
PROFILE.titles[title.npCommunicationId].trophies = trophyData.trophies; //any where from 10 - 50+ of these, for looped
Problem is, if I want to have multiple profiles, this doesn't work as it just inserts them in the same profile. I need 'PROFILE' to be an array that has all the above elements at each index.
PROFILEarray[n].profileData = {};
PROFILEarray[n].profileData.onlineId = profileData.onlineId;
PROFILEarray[n].profileData.region = profileData.region;
Something like this is what I need^
But for the above I get this error
Cannot read property 'profileData' of undefined
Once this is complete, it's saved into a file in JSON format to then be used by PHP code I've written to insert into a db.
This is a small snippet of the json output: http://textuploader.com/5zpbk (had to cut, too bit to upload)
you must define PROFILEarray[n] as object. JavaScript objects are containers for named values. You can not set value of undefined
PROFILEarray[n] is undefined in this case. Initialize it as {}(object)
Try this:
var PROFILEarray = [];
for (var n = 0; n < 5; n++) {
PROFILEarray[n] = {};
PROFILEarray[n].profileData = {};
PROFILEarray[n].profileData.onlineId = n;
PROFILEarray[n].profileData.region = 'Region' + n;
}
alert(JSON.stringify(PROFILEarray));
I know JavaScript passes Objects by reference and thus I'm having a lot of trouble with the following code:
function doGradeAssignmentContent(dtos) {
var x = 5;
var allPages = [];
var stage = new App.UI.PopUpDisplay.PopUpStageAssignmentGrader(null, that);// pass launch element
for(var i = 0; i < dtos[0].result.students.length; ++i) {
var pagesSet = [];
for(var j = 0; j < dtos[0].result.questions.length; ++j) {
var questionObject = jQuery.extend(true, {}, new Object());
questionObject = dtos[0].result.questions[j];
if(dtos[0].result.students[i].answers[j].assignmentQuestionId === questionObject.questionId) {// expected, if not here something is wrong
questionObject.answer = dtos[0].result.students[i].answers[j].studentAnswer;
questionObject.pointsReceived = dtos[0].result.students[i].answers[j].pointsReceived;
} else {
var theAnswer = findAssociatedStudentAnswer(questionObject.questionId, dtos[0].result.students[i].answers[j]);
if(theAnswer !== null) {
questionObject.answer = theAnswer.studentAnswer;
questionObject.pointsReceived = theAnswer.pointsReceived;
} else {
alert("Unexpected error. Please refresh and try again.");
}
}
pagesSet[pagesSet.length] = new App.UI.PopUpDisplay.StageAssignmentGradingPages[dtos[0].result.questions[j].questionType.charAt(0).toUpperCase() + dtos[0].result.questions[j].questionType.slice(1) + "QuestionAssignmentGradingPage"](j + 1, questionObject);
}
var studentInfo = {};
studentInfo.avatar = dtos[0].result.students[i].avatar;
studentInfo.displayName = dtos[0].result.students[i].displayName;
stage.addPageSet(pagesSet, studentInfo);
}
stage.launch();
}
First let me show you what the result (dtos) looks like so you can better understand how this function is parsing it:
The result (dtos) is an Object and looks something like:
dtos Array
dtos[0], static always here
dtos[0].result, static always here
dtos[0].questions Array
dtos[0].questions.index0 - indexN. This describes our Questions, each one is an Object
dtos[0].students Array
dtos[0].students[0]-[n].answers Array. Each student array/Object has an Answers array. Each student will have as many elements in this answers Array that there were questions in dtos[0].questions. Each element is an Object
Now what we do in this here is create this Object stage. Important things here are it has an array called "this.studentsPages". This array will ultimately have as many entries as there were students in dtos[0].students.
So we loop through this for loop disecting the dtos array and creating a pagesSet array. Here comes my problem. On the first iteration through the for loop I create this questionObject element. I also have tried just doing var questionObject = {}, but what you see now was just an attempt to fix the problem I was seeing, but it didn't work either.
So at the end of the first iteration of the outer for loop I call stage.addPageSet, this is what happens here:
var pageObject = [];
pageObject["questions"] = pageSet;
pageObject["displayName"] = studentInfo.displayName;
this.studentsPages[this.studentsPages.length] = pageObject;
if(this.studentsPages.length === 1) {// first time only
for(var i = 0; i < pageSet.length; ++i) {
this.addPage(pageSet[i]);
}
}
The important thing to take notice of here is where I add pageObject on to this.studentsPages which was an empty array before the first call. pageObject now has pageSet plus a little bit more information. Remember, pageSet was an Object and thus passed by reference.
On the next iteration of the for loop, when I hit this line:
questionObject.answer = dtos[0].result.students[i].answers[j].studentAnswer;
It goes wrong. This changes the local copy of questionObject, BUT it also changes the copy of questionObjec that was passed to addPageSet and added to the studentsPages array in the first iteration. So, if I only had 2 students coming in, then when all is said and done, studentsPages hold 2 identical Objects. This should not be true.
The problem is questionObject in the doGradeAssignmentContent function is keeping a reference to the Object created on the previous iteration and then overrides it on all subsequent iterations.
What can I do to fix this?
Thanks for the help!
With out having looked at it too closely I believe you need to change the following:
// Before:
var questionObject = jQuery.extend(true, {}, new Object());
questionObject = dtos[0].result.questions[j];
// After:
var questionObject = jQuery.extend(true, {}, dtos[0].result.questions[j]);
I didn't look too closely if there are other instances in the code where this needs to be applied, but the core concept is to utilize jQuery's deep copy to generate a duplicate of the object you do not wish to retain a reference to.
I'm pulling data with Ajax that changes every day. I want to package the data into objects that have unique names. Currently I created a constructor that looks like something like this:
function myObject(Id,thing1,thing2,thing3)
{
this.Id = Id;
this.thing1 = thing1;
this.thing2 = thing2;
this.thing3 = thing3;
}
then I push that to an array in a loop like this
for(var i=0; i<data.length; i++)
{
array.push(new myObject(value1,value2,value3,value4));
}
This works fine for what I'm doing but I just get an array with [object,object,object,object] inside of it which I can access with array[0] , array[1], etc.
but now I want to store those objects in firebase and would need to reference them so how could I have them named uniquely?
normally you would do
var thingid1 = new myObject(value1,value2,value3,value4));
var thingid2 = new myObject(value1,value2,value3,value4));
but this is all being created on the fly and sometimes there is 1 object created and sometimes 10.
I'm new at this and I've looked everywhere so any help would be appreciated.
If your Id (value1) is unique...
var myObjectContainer = {};
for(var i=0; i<data.length; i += 1)
{
myObjectContainer[value1] = new MyObject(value1,value2,value3,value4);
}