Reputation: 599
function getDataSets(data){
console.log(data);
for(key in data){
console.log(key,data[key]);
}
}
I am passing a JavaScript Object (data) to the function getDataSets
, when I do console.log(data)
I am able to see the object contents - I am able to expand the value of each key (in the Console) and look at their values (which are in turn JavaScript Objects) , as expected. But when the for loop runs over each key and I try to print out the value of each key - I am getting something like <key name> Object {}
but value of the key is not an empty object. I guess I am missing something trivial here. Can someone help me out with this?
This is the output I get for console.log(data)
Object {key1: Object, key2: Object, key3: Object, key4: Object, key5: Object}
Even data[key1]
is giving me an empty object.
Output for console.log(JSON.stringify(data, null, 3))
is
{
"key1": {},
"key2": {},
"key3": {},
"key4": {},
"key5": {}
}
The weird part is that when I run getDataSets(data)
directly from the console again , that is if I type directly in the console something like d = getDataSets(data)
I am getting the expected output ,the value of the key are non-empty JavaScript Objects.
EDIT-
function getData(platforms){
var data = {};
$.each(platforms,function(index,platform){
data[platform] = {};
var req = new XMLHttpRequest();
req.onload = function(){
//Here is the place each key of data is getting its value assigned
};
req.open('get',<some url>,true);
req.send();
})
return data;
}
I am using this getData
function to get the data
and am sending this to getDataSets
. I think problem is that the URL to which getData
is requesting is taking some to load,I guess. So it is passing the data
even before the URL has been requested,that is why its key has an empty object initialized. But then console.log(data)
should not work right?
Upvotes: 0
Views: 513
Reputation: 1064
The code you posted looks good. I'm guessing there's something elsewhere in your code that is changing the value of "data" or "key". I ran this code, and it works fine for me in Chrome:
<script type="text/javascript">
var tmp = {abc: "123", def: {nested: "blah"}, xyz: 456 };
function test(data) {
console.log(JSON.stringify(tmp, null, 3));
for (x in tmp) {
console.log(x, tmp[x]);
}
}
test(tmp);
</script>
Thanks for posting the additional code, now I see the problem. You're returning the "data" object before the XMLHttpRequest returns. You'll need to store the "data" object in a scope outside of the "getData" function. The "data" object won't be populated until the "onload" handler is called. (Put your logging in the "onload" handler to see what's happening.)
Also be careful, since you're making multiple XMLHTTPRequests, you'll need to keep track of the requests, so you know when all the requests are complete. (They may return in any order.)
Upvotes: 1