Reputation: 15006
I have a variable that may contain objects or may be undefined. I wish to add additional objects to this variable. How do I do that?
code example when applicable:
function(){
var comments;
if(fbposts[fbpost].comments.count){
for(var comment in fbposts[fbpost].comments.data){
comments = ({
name: fbposts[fbpost].comments.data[comment].from.name,
link: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id,
img: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id+"/picture",
message: fbposts[fbpost].comments.data[comment].message,
created: timeDifference(Date.parse(fbposts[fbpost].comments.data[comment].created_time)),
})
}
}
return comments;}(),
Upvotes: 1
Views: 79
Reputation: 150030
Test if it is undefined and if so assign it to an empty object:
if (typeof yourVar === "undefined")
yourVar = {};
yourVar.additionalObject1 = { something : "test" };
yourVar.additionalObject2 = { something : "else" };
EDIT: OK, now that you've added code to your question, it seems like your comments
variable should be an array, since you are adding to it in a loop. So I think you'd want to do something like this:
(function(){
var comments = [];
if(fbposts[fbpost].comments.count){
for(var comment in fbposts[fbpost].comments.data){
comments.push({
name: fbposts[fbpost].comments.data[comment].from.name,
link: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id,
img: "http://www.facebook.com/"+fbposts[fbpost].comments.data[comment].from.id+"/picture",
message: fbposts[fbpost].comments.data[comment].message,
created: timeDifference(Date.parse(fbposts[fbpost].comments.data[comment].created_time)),
});
}
}
return comments;
})();
comments
will thus contain one element for each comment in your source data. If there are no comments it will be an empty array. (If you want it to return undefined
if there are no comments then leave the variable declaration where it is as var comments
and add comments=[];
just inside the if
statement.)
Upvotes: 2
Reputation: 11096
If you're using jQuery (and why wouldn't you be?), then you want to look at $.extend()
http://api.jquery.com/jQuery.extend/
Upvotes: 0