While iterating over the key with a variable in a loop, only one property is displayed consistently instead of four different

Currently, I am working on creating an address book using JavaScript. The problem I am facing is that the properties of my objects are not providing me with the necessary information. I need 4 different properties instead of 4 loops with the same property.

The for loop is creating a loop of 4 li list items based on the information stored in the objects.

However, all I am getting is EMAIL repeated in each loop.

I hope you understand the issue and can offer your assistance. Below is the code snippet:

    // Contact list function
function Contact(fname, lname, address, email) { 
    this.fname = fname;
    this.lname = lname;
    this.address = address;
    this.email = email;    
}

// Contacts
var tony = new Contact("Tony", "Stark", "Avengers 123", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e37703f3370372c3130333f301e36312a333f3732703d3133">[email protected]</a>");
var steve = new Contact("Steve", "Rogers", "Avengers 12", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e5e7f6a8e7ebe3f4efe5e7c6eee9f2ebe7efeaa8e5e9eb">[email protected]</a>");

// All contacts
var contacts = [tony, steve];

// Appending the objects
var body = document.getElementsByTagName('body')[0];
var ul = document.createElement('ul');
body.appendChild(ul);

function theContacts() {
var li = document.createElement('li');

    li.innerHTML = tony.fname + ' ' + stark.lname;
    ul.appendChild(li);
        for (i = 0; i < 4; i++) {
        li = document.createElement('li');

    for (var key in tony) {
        li.innerHTML = key;
    }
        ul.appendChild(li);

    }
}

// Calling the object
theContacts();

Thank you for your support!

Answer №1

To display all the contacts along with their attributes in nested unordered lists, I have applied specific class names for styling convenience. You should start implementing this code right below where you declare your variable contacts.

function displayContacts() {
    var bodyElement = document.getElementsByTagName('body')[0],
        outerList = document.createElement('ul'),
        contactLength = contacts.length;
    outerList.className = 'contact-list';
    for (var j = 0; j < contactLength; j++) {
        var currentContact = contacts[j],
            listItem = document.createElement('li'),
            innerList = document.createElement('ul');
        listItem.className = 'individual-contact'; 
        listItem.innerHTML = currentContact.firstName + ' ' + currentContact.lastName;
        innerList.className = 'info-list';
        for (var attribute in currentContact) {
            var infoItem = document.createElement('li');
            infoItem.className = attribute;
            infoItem.innerHTML = currentContact[attribute];
            innerList.appendChild(infoItem);
        }
        listItem.appendChild(innerList); 
        outerList.appendChild(listItem);
    }
    bodyElement.appendChild(outerList);
}

The issue that you encountered was due to the confusion between var listItem inside the function displayContacts().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Use jQuery to update the field without affecting the observable

Greetings to the wonderful stackoverflow community! I recently delved into using knockout just a few days back. Currently, I am utilizing it to create a dynamic menu builder for a CMS project that I'm deeply engrossed in. If you'd like to take ...

Show a pop-up notification when the mouse passes over a word in the text

I've been grappling with this issue for days now and could really use some guidance. Despite scouring the web, I'm unsure if I've approached it correctly. What I'm trying to achieve is having an alert box pop up each time a user hovers ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

JavaScript can be used to create a fullscreen experience without any toolbars, scrollbars, and the like, without having

Is there a way for me to expand the current window I am using to fullscreen mode and eliminate all toolbars? ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

Determine distinct items in an array that match a predefined criteria

I have a list of objects with two keys, img1 and img2. I need to identify unique objects based on the values of img1, while also retaining the corresponding value of img2. This is the current code I am using: const imgs_arr = [ ...new Set( inpu ...

When you access the `selectedIndex` property in JavaScript, it will return an object of type `HTMLSelect

I am currently working on a piece of code that retrieves the value from dropdown list items and then displays it in the document. To proceed, please select a fruit and click the button: <select id="mySelect"> <option>Apple</option ...

Using AngularJS to retrieve DOM elements within a directive's controller

Currently, I am in the process of creating a custom image carousel directive using only AngularJS and no additional libraries. simpleCarousel.$inject = []; function simpleCarousel() { var directive = { restrict: 'E', templat ...

Creating copies of a loop or function, and appending the outcomes to a dataframe iteratively

After writing an R loop and transforming it into a function that takes in a dataframe, here is the original code and data frame. The objective is to execute this function or loop 1000 times and generate a data frame with 1000 columns representing row sums ...

What is the best way to calculate the total of all files within a folder structure using JavaScript

Here is the array I'm working with: Array (7812) 0 {foldername: "", amount_of_files: 12, children: 86} 1 {foldername: "/pm", amount_of_files: 3, children: 7} 2 {foldername: "/pm/css", amount_of_files: 1, children: 0} 3 {f ...

Running JavaScript code along with HTML elements extracted from a jQuery ajax callback

Alternatively, not exactly "executing," but rather updating a pre-existing function with a function returned in the response. Step 1 I have an HTML5 page detailing a specific location. The server-side includes a ColdFusion file called "MapFunction.cfm" ...

What is the most effective way to save numerical information to a file?

Imagine a scenario where there is an array filled with one million random numbers: [ 0.17309080497872764, 0.7861753816498267, ...] The task at hand is to store these numbers onto a disk for future retrieval. While storing them in text formats like JSON or ...

Clicking through the button inside Vuetify's text-field append slot

While working on creating Vuetify's v-text-field with a slot named append containing a button, everything seems to be functioning correctly except for the fact that when I click the button, it goes through and focuses on the text field. On mobile devi ...

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

Adding a custom property to a React component

Currently, I am facing an issue while attempting to modify an MUI component. Everything works smoothly until I execute the build command, at which point it fails. I have experimented with a few variations of this, but essentially I am looking to introduce ...

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

Turning off strict mode in the bundling process of React with webpack can be achieved by following

I'm facing an issue with my application. It works perfectly in all browsers except for IE, where it throws the following error: 0x800a0416 - JavaScript runtime error: Multiple definitions of a property not allowed in strict mode In my webpack.config ...

Use Jquery to apply quotation marks within a blockquote

Here is the code I am working with: $("input[id="+id.slice(0,-1)+"-br-"+brand+"].qnt_to_cart").show(); This code generates: input[id=02620-br-FEBI BILSTEIN].qnt_to_cart However, I need it to look like this instead: input[id="02620-br-FEBI BILSTEIN"].q ...

Does React JS set initial value after re-rendering its state?

Every time the state is updated, the function is triggered once more (please correct me if I am mistaken). And since the initial line of the App function sets the state, the values of data and setData will not revert to their defaults. For instance, i ...

Developing a compressed file in JavaScript

async purchaseMultiple(decoded, purchaseData){ const user = await Database.user.findOne({where: { id_user: decoded.id_user }}); if( ! user) return [404, 'ERROR: User [' + decoded.id_user + '] not found']; if(user.credi ...