I am learning object manipulation and am practicing by making an 'address book' that takes name values, add's them to an object, loads the object into an array, and then outputs the list of names.
Everytime I try to output the list of names it comes out like this:
"0: [object Object]; "
I tried JSON.stringify and that did not work. How do I output the object to the DOM? I want to display all of the objects within the array.
Javascript:
var allInfo = []; //Store names (as objects) here
var output = printList('output');
var cache = [];
var numOfNames = 0;
var nameCounter = 0
alert("JS Works");
function buildList() { //Makes a new object, and pushes it to the 'allInfo' Array
var info = {};
info.firstName = document.getElementById('firstName').value;
info.middleName = document.getElementById('middleName').value;
info.lastName = document.getElementById('lastName').value;
allInfo.push(info);
addName(1);
clear();
alert("Logged");
}
function resetList() {
allInfo = [];
numOfNames = 0;
nameCounter = 0;
addName(0);
blankOut();
}
function blankOut() {
document.getElementById('output').innerHTML = " ";
}
//Problem Function
function generate(o) { //Here is where I am having trouble.
var out = ''; // This is supposed to output a list of names but doesnt.
for (var p in o) {
out += p + ': ' + o[p] + '; ';
}
document.getElementById('output').innerHTML = (JSON.stringify(out, null, 4));
}
function addName(x) {
if (x > 0) {
nameCounter++;
numOfNames = nameCounter;
document.getElementById('numOfNames').innerHTML = numOfNames;
} else {
nameCounter = 0;
numOfNames = 0;
document.getElementById('numOfNames').innerHTML = numOfNames;
}
}
function printList(x) {
var output = getById(x);
return function (text) {
output.innerHTML += text + '\n';
};
}
function getById(x) {
return document.getElementById(x);
}
function clear() {
document.getElementById("firstName").value = "";
document.getElementById("middleName").value = "";
document.getElementById("lastName").value = "";
}
Not a duplicate: Not a duplicate. I am trying to do the opposite. I am trying to output all properties and values FROM and array/object to the DOM. I know how to 'grab' them from the DOM as the other link addresses, I am trying to regurgitate the array/object, so the opposite.
JSFiddle link here: https://jsfiddle.net/jeffward01/zfv1zy50/