Traversing within an entity

I came across something confusing to me within the for loop:

var info = {
"full_name" : "John Doe",
"title" : "FrontEnd",
"links" : {
    "blog"     : "JohnDoe.com",
    "facebook" : "http://facebook.com/JohnDoe",
        "youtube"  : "http://www.youtube.com/JohnDoe",
        "twitter"  : "http://twitter.com/JohnDoe" 
    }
};

When running through this object with the following loop:

var output = "";

for (var key in info.links ) {
    if (info.links.hasOwnProperty(key)) {
        output += '<li>' +
        '<a href = "' + info.links[key] +
        '">' + key + '</a>' +
        '</li>';
        console.log(key);
    } 
}
var update = document.getElementById('links');
update.innerHTML = output;

My question is, what exactly is var key in this loop and how does it work without defining var key within the scope of this loop? In this scenario, var key takes on the values blog, facebook, etc. inside the info.links object. But why does it behave this way?

Answer №1

Make sure to check out this guide on using for...in loops in JavaScript

for (variable in object) { ...
}

Each iteration assigns a different property name to the variable. Your property names could be "facebook", "twitter", and so on within your object.

Answer №2

let signifies the creation of a new variable, with name being the identifier for this variable.

As you iterate through all elements within data.links, it is important to uniquely reference each let.

Answer №3

Check out this for a possible solution. The key in this context refers to the keys within the info.links object such as blog, facebook. Therefore, when we use info.links[key], we are accessing the corresponding value.

info.links["blog"] = "JohnDoe.com",
info.links["facebook"] = "http://facebook.com/JohnDoe"

I hope this clarifies things.

For more information on looping through JavaScript objects, take a look at this guide.

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

Ways to trigger an AngularJS event from a popup?

Situation: I am working on an AngularJS application that utilizes Google's authentication feature. Depending on the specific resource, when Angular communicates with my backend, it may request an Oauth token. In such cases, Angular will display a po ...

Page can be accessed using file_get_contents function but not with cURL

In the process of creating an API endpoint in PHP, a scenario arose where JSON data output from a specific page example.com/stats was causing issues with cURL requests compared to using file_get_contents(). How can I ensure that JSON data served in PHP is ...

Trouble accessing onclick function

My dataSend AJAX function is not being called when I use the onclick event. I have checked in the Inspector of my browser and confirmed that the click handler is attached to it. However, when I set a breakpoint in the function using the Debugger, it never ...

JavaScript Functions Not Being Executed by Onclick Event in Internet Explorer 8

When a user clicks, I need two functions to run. This works in Firefox and Chrome, but not in IE8. The first function should display a modal (indicating that the form is being saved, although it's not showing up) while the second function saves the f ...

Obtain the accurate data type value from a JSON dictionary

Is there a way in Objective-C to extract the specific data type from a JSON dictionary? For instance, consider this JSON structure: { "ret": 0, "state": "Italy", "lat": 45.46347, "lon": 9.19404 } I need to retrieve an INT value for "ret ...

Leveraging WebWorker in Azure DevOps WebExtension

I am attempting to employ a WebWorker within a WebExtension on an Azure DevOps Server. Data processing for a large repository can be quite resource-intensive, prompting me to utilize a WebWorker for background calculations. However, when I try to instant ...

The system does not acknowledge 'CI' as a command that can be used internally or externally, functioning program, or batch file

Every time I attempt to execute npm run build in my React project, a persistent error keeps popping up: 'CI' is not recognized as an internal or external command, operable program or batch file. I have exhausted all troubleshooting steps - fro ...

Revise if a specific file is not being called by AJAX

I am currently utilizing a routing library known as Grapnel.js. It requires URLs in the format of index.php#something/something, which is why I am using htaccess to rewrite /something/something to match that structure. However, I would like the flexibility ...

CSS3 transition applied to a jQuery direction-aware hover effect

I'm encountering difficulties making direction-aware hover and css transitions function correctly. Specifically, I am attempting to create a grid of elements with front and back faces, and on hover, have a css transition that flips the element to disp ...

What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code: Inside blog.js import post1 from './blog-post.1.md'; . . . return( <Main>{post1}<Main/> ...

Step by step guide to implementing form step validation in a multi-step jQuery form with radio buttons

I have implemented the sample code provided in this link, with the addition of 2 extra form steps: LINK TO SAMPLE FORM My form consists of radio buttons (2 per page) instead of text boxes. How can I ensure that each form page is validated so that the for ...

Enhance Your R Shiny Leaflet with JavaScript Addons for Stunning Heat

I am currently exploring the use of a javascript addon for leaflet called the heatmap functionality, which can be found at https://github.com/Leaflet/Leaflet.heat. My goal is to integrate this feature into Shiny, however, it seems that the leaflet package ...

Access data from an array within an object using DataTables

Here's a simple question: How do I access an array inside an object using datatables? Object I am trying to access the array "data" : { "success": true, "data": [ { "id": "4", "tienda_id": "5", "tienda_nombre": "sad", ...

Is there a way to retrieve a string using the HTTP session in JavaScript?

I am currently developing a chat application using web API ASP.NET with C# in VS Code. The user registration and login functionalities are working seamlessly with the database. I have integrated the SignalR sample code into the Welcome page, but I have a s ...

Slickgrid's scrollRowIntoView function isn't behaving as anticipated

Here is my code that utilizes the scrollRowIntoView function. I am making use of the resizer to adjust the grid's length to match the browser window. Currently, I have hardcoded a number as an example, but eventually, I will fetch the record to be scr ...

What is the best approach to effectively define conditional statements utilizing AND, OR in JSON format?

If I have an expression such as: ( A >= 10 && B == 20 ) || ( C < 30 ) || ( D != 50 ) I propose the following JSON structure to represent and store this expression: { "filter": [ { "var":"A", "condition":"ge", "num":10 }, ...

Transfer the text link to the following page

In the web project I'm working on, I created a tagcloud. The goal is when a user clicks on a tag, it should redirect to the page showRecipesFromTags.php. <form name="tagform" id="tagform" method="get" action="/showRecipesFromTags.php"> <?php ...

What is the best way to transform the pages extracted through the Notion API into slugs?

I'm new to Next.js and Notion API, and I want to create a blog site on my personal website using the Notion API. While I can easily pull the posts, I am facing a challenge in slugifying the endpoint IDs with post titles. When attempting this based on ...

Unique SQL Table Rows with Individual Comma Separation

In my database, I have a table named b_topics which includes a tags column with multiple rows. id | tags 1 | Joshua, Janet, Hannah 2 | Glory, Jon, Celina, Johanna 3 | Bridge,Terry, Sterling 4 | Daniel, Florence, Joanne I am trying to find related t ...

Guide on adding additional key-value pairs to an already existing elastic document using Python

I attempted to use the standard _update method in Elastic but it is not working as expected. data_to_send ={ "new_key1": new_value1, "new_key2": new_value2, "new_key3": new_value3 } response = re ...