Skip to content

Instantly share code, notes, and snippets.

@dzenkovich
Created October 21, 2013 07:35
Show Gist options
  • Save dzenkovich/7079946 to your computer and use it in GitHub Desktop.
Save dzenkovich/7079946 to your computer and use it in GitHub Desktop.
JS Core: Task 2. Objects Session
(function () {
/**
* Gets the object value from the session storage or cookies and displays the result
*/
window.onload = function() {
var resultBox = document.getElementById('result'), //gets the DOM element where results are stored
key = 'person', // the key name of the object
result = sessionDataManager.getObject(key); //gets the value of the object from session storage or from cookies
// appends the reult to the resultBox element
if (result) {
resultBox.innerHTML = 'The object "' + key + '" has properties: <br/>' + printObject(result).join(', ');
}
else {
resultBox.innerHTML = 'Cookie or session store item with the name"' + key + '" doesn\'t exist.';
}
/**
* Gets the array of the object properties and their values
* @returns {Array} - the array of the object properties and their values
*/
function printObject(object){
var collection = [], index = 0, next;
for(var item in object){
/* Checks if the object has property "item", it's important to use method hasOwnProperty()
when iterating over object properties to filter out properties that come with prototype inheritance */
if(object.hasOwnProperty(item)){
next = object[item];
/*Checks if the property of the object is the object itself and is not null.
If it's true the function is called recursively, as it is unknown the depth of nesting in the object.
Otherwise the result is assigned to the item of the array "collection"*/
if(typeof next === 'object' && next !== null){
collection[index++]= item + ': { ' + printObject(next).join(', ') + '} ';
}
else collection[index++] = [item + ': ' + next.toString()];
}
}
return collection;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment