JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP.

This is an example of my json:

{
    'username': 'Karl',
    'email': '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="542c2d2e143536377a2c2c">[email protected]</a>',
    'user_id': 5,
    ...
}

I have span elements on my page with a data-field attribute. For example:

<span data-field="username">xyz</span>

The json-array is returned from an ajax-request and I want to replace every element where the data-field="" matches the array-index.

Currently, I am doing this for each element in the json-array:

$("[data-field='username']").text(data.username);
$("[data-field='email']").text(data.email);

But as the number of elements increases, this approach becomes messy. Are there any other alternatives? I've heard about transforming the json into an object, but I'm not sure how to do it.

Answer №1

Here is an example of a for each loop in JavaScript that iterates through a JSON object:

for(var property in jsonData){
   $("[data-field='"+ property +"']").text(jsonData[property]);
 }

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

Vue.js enhances user input interactions

CSS <span :style="{ display : displayTitle }" @click="toggleInput()"> {{ text }} </span> <input v-if="isEditing" type="text" v-model="text" @blur="hideInput" @keydown.enter="saveChanges" @keydown.esc="cancelE ...

Mutating properties in VueJs

When I attempted to move a section for filtering from the parent component to a child component, I encountered this error message: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a ...

"Navigate through the page by scrolling with your mouse all the way to 100

Is it possible to trigger an action when a user starts scrolling using the mousewheel? I've searched online but all I found was information on 100% scroll on click. I want the window to automatically be scrolled down to 100% as soon as the user starts ...

Encountering Error 500 in IBM Notes Client while working with XPages and REST Services

Trying to retrieve a JSON representation of a view using an ajax request from a XPage. Initially, I used the URL https://myserver/mydb/myview?readviewentries&outputformat=JSON&count=-1, which worked in browsers but not in the IBM Notes Client. I en ...

Troubleshooting problem with Ajax Calendar Extender

I have a text box where I need to save the chosen date from a calendar. To achieve this, I am using an AJAX calendar extender and setting the target control property to the textbox ID. However, when I click on a button on the same page, I lose the selected ...

What is the best way to confirm that a JSON node contains child nodes with specific values assigned to them?

Within my JSON String, the structure looks like this: json = "{\"Things\": \n" + " {\"Thing\": {\n" + " \"ID\":\"123\",\n" + " \"name\":\"Yet Another Thing ...

The button similar to Facebook does not function properly when using fancybox

My photo gallery uses fancybox, and when fancybox is open a like button appears outside the title. However, the Facebook like button doesn't seem to work. Here is my JavaScript code: $(".fancyboxi").fancybox({ padding: 0, openE ...

React - Highcharts Full Screen dark overlay

I am currently working on integrating highcharts/highstock into my application, and I have encountered an issue with the full screen functionality. The challenge I am facing is setting a fixed height for my charts while also enabling the option to view ea ...

What are some techniques for identifying duplicate HTML element IDs?

I encountered a challenging bug that took a lot of effort to resolve, only to discover that it was due to two HTML elements having the same ID attribute. Is there a command available to identify duplicate IDs throughout the entire DOM? Update: After rev ...

Utilize string paths for images instead of requires when resolving img src and background-image URLs

I have successfully implemented image loading with webpack using the file loader, but only when I require or import images. I am curious about how create-react-app achieves the functionality where everything in the public folder is accessible, for example, ...

When reopening the modal in Bootstrap V5 with jQuery, the close event may not trigger as expected

When trying to implement special functionality in my modal close event using sweetalert2, I encountered an issue where the close event does not trigger again after closing the modal for the first time. Check out a live example here: https://codepen.io/th ...

Updating content with jQuery based on radio button selection

Looking for assistance with a simple jQuery code that will display different content when different radio buttons are clicked. Check out the code here. This is the HTML code: <label class="radio inline"> <input id="up_radio" type="radio" n ...

How to efficiently retrieve data from a JSON file stored on an SD Card and showcase the information on a textview using Android?

I have a text file stored in my SdCard and I want to parse it using a Json parser. Once parsed, I would like to display the data in my textview. How can I achieve this? { "data": [ { "id": "1", "title": "Farhan Shah", "duration ...

Utilizing Struts 1 alongside AngularJS

My frontend JSP includes the following code: <label>{{metadata[key].displayName}}:</label> This code successfully displays the value. However, this value actually acts as a "key" for an ApplicationResource defined in the Struts 1 framework. U ...

What is the best way to handle waiting for a JavaScript __doPostBack call in Selenium and WebDriver?

I am encountering a unique issue while automating with Selenium/Python and trying to input data into two fields on a website. The script fills out the first field, ORIGIN CITY, without any problems. I have used WebDriverWait for the second field, DELIVERY ...

Incorporating Javascript into a .Net MVC 3 Project

It seems like there should be a straightforward solution to my question, but I'm struggling with it. I have an animation.js file that includes dependency_1.js and dependency_2.js in an include folder. Within my animation.js file, I load these dependen ...

What is the best way to obtain the attribute value when a user clicks on a child element?

Is there a way to retrieve the value of the data-custom attribute when the red square is clicked without having to add the same attribute to nested elements? This can become cumbersome if there are multiple levels of nesting. class Example extends React ...

Adjust the sizing of all fonts following the switch in font styles

Seeking help for adjusting font-size across a responsive web page design using different font families. font-family:Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", serif; To achieve responsiveness, various media queries were applie ...

Retrieve information from a dropdown menu that is dependent on the selected value from another dropdown

   Check out this sample API data - I currently have three dropdown menus set up: From Release To Release Compatibility When a specific from release is selected, all corresponding to releases associated with that specific from release should be displ ...

Having trouble displaying toasts on my website using Angular Material design and $mdToast

Hello there, I am very new to AngularJS, and I have just started using the basic function Show() from $mdToast. Below is the complete code that I have written for this issue, and I would greatly appreciate any help you can provide. 'use strict&apos ...