Why is it difficult to parse out a single object using jQuery .each, while multiple objects work perfectly?

Currently, I am dealing with a .each loop that processes an object retrieved from a JSON feed through Ajax (Type: jsonp; the success function sends the "data" to the function/method containing the .each loop).

The issue puzzling me is that when the feed returns multiple sets of data, it parses them correctly. However, if it only returns one set of data, the loop attempts to break down the individual fields of that lone record as if each field were a record itself.

Below are examples of the objects received from the Ajax routine:

Example 1: -- single item

{
  "SmeDetail": {
    "SipAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf6fd2ff105efdf4e8fcfe81fdfcfeeb">[email protected]</a>",
    "SubjectExpert": "Smith, John",
    "SubjectMatter": "JavaScript"
  }
}

Example 2: -- multiple items

{
  "SmeDetail": [
    {
      "SipAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0d6c2d7dcd091ddd5ccd3d8d4d390d0d3b0fccbd0fed3dcddc6d0dad195"><em>[email protected]</em></a>",
      "SubjectExpert": "Doe, Jane",
      "SubjectMatter": "HTML"
    },
    {
      "SipAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="48796474737c646933767270677377697332777365323e737f7d">[email protected]</a>",
      "SubjectExpert": "Doe, John",
      "SubjectMatter": "CSS"
    }
  ]
}

Now, let's look at the .each routine:

$.each(json_data.SmeDetail, function (i,val){
  var sip_address = val.SipAddress;
  var SME_name = val.SubjectExpert;
  var subject_matter = val.SubjectMatter;
  var sip_link = "<a href='sip:" + sip_address +
      "'><img src='http://server/prod/images/im.gif' hspace='2' border='0'  title='Send an instant message to " + 
      SME_name + "' alt='Send an instant message to " + 
      SME_name + "'/></a>";
  output7 = output7 + "<tr><td>" + 
      SME_name + " " + sip_link + "</td></tr>";
});

I inserted some alert statements for verification purposes. When this runs for a single record from the feed, it incorrectly loops three times and assigns "undefined" to all variables. The fact that it loops exactly three times and enters the loop indicates that it recognizes a "SmeDetail" record but treats each individual field as a separate record.

This makes me question the structure of the single-record return. Should there be brackets around that sole item?

Answer №1

const profile = userData.profileDetails;
if (!profile.length) { profile = [profile] };
$.each(profile,....

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

Every time I restart the server with MEN stack, I encounter an error message stating "Cannot read property 'name' of null"

I am currently working on developing a campgrounds application based on Colt Steele's Udemy course "The Web Developer Bootcamp". Everything is going smoothly except for one issue I encountered. When I restart the server and directly access the URL wit ...

How to Store and Retrieve User-specific Data using Express and Mongoose?

Currently, I am developing a small single-page application that allows users to login using PassportJs and Mongoose. One of the main features I am working on is enabling users to log in and have a unique todo/task list associated with each user. I succes ...

What is the process for creating a button click listener event in Kotlin or JavaScript?

While working in IntelliJ IDEA, I have created a button in my HTML file with an ID. My goal is to change the header tag to say "button clicked" using Kotlin. After searching through kotlinlang.org and other resources, I am struggling to find a simple refe ...

Issue with loading contentsCss in CKEDITOR with VUEJS2

Currently in the process of developing a website using Vue.js 2, we incorporated the ckeditor4-vue plugin some time ago. An issue has recently come up regarding the font not matching the rest of the application. The preference is to default to 'Lato& ...

What is the reason for the Circle to Polygon node module producing an oval or ellipse shape instead of a circle shape?

I've been experimenting with the npm package circle-to-polygon and I crafted the following code to generate a polygon that resembles a circle. const circleToPolygon = require('circle-to-polygon'); let coordinates = [28.612484207825005, 77. ...

Is there a way to dynamically assign column names during the import process?

In my current scenario, I am importing data from various sources into my JSON backend. The mapping file will resemble the sample below. The question is how can I efficiently utilize this mapping during data import into my backend. The idea is to provide t ...

React/JavaScript: Leveraging the power of React spread for simultaneously making two modifications to an array

I need to update the key/value pair 'timestamp' in my array and rename it to 'start'. In addition to adding an 'id' to each item with a value, I would like to change 'timestamp' to 'start'. Can this be achi ...

Exploring Angularjs: Retrieving the value of a selected optgroup

When using my application, I need to extract the selected optgroup value from a dropdown menu. Here is the sample code: HTML: <select ng-model='theModel' ng-change="display(theModel)" > <optgroup ng-repeat='group in collectio ...

Enveloping an immediate search within a JavaScript throttle function

Below is a code snippet for a cloud tag (Goat1000) with an instant query. The query part should be enclosed within the throttle function from the underscore.js library to prevent server crashes. <script src="underscore-min.js"></script> &l ...

Connecting a pre-existing Angular 2 application to a Node.js server: A step-by-step guide

I am currently working on an Angular 2 application with the following structure : View Structure of my Angular app Furthermore, on the server side : View Structure of server app I have noticed that there are two module dependencies folders, but I am un ...

What is the method for invoking a function with a chosen date in the @syncfusion schedule with Angular 9?

capture of calendar display I am looking for a way to trigger a function with the selected date as a parameter. However, I am unable to locate the appropriate event to use within this module. Can someone provide assistance with this issue? Thanks! ...

Calculate the total of all values associated with a dynamically generated key within an array of objects

I'm trying to calculate the sum of similar keys in an array of objects. Each object in the array will have some common keys, but not all arrays will share the same set of keys. I'm considering storing these keys in a separate array and then loopi ...

Capturing click events on a stacked area chart with nvd3

Could someone assist me in capturing the click event on a nvd3 stacked area chart? I have successfully managed to capture tooltip show and hide events but am struggling with the click event. How can I obtain information about the clicked point? Please help ...

Implementing Vue.js Popover for Individual Dropdown Items: A How-To Guide

I need unique information text to display for each dropdown item when hovered. I am using bootstrap-vue and have a loop set up for the dropdown items. <b-dropdown :text="currentColorType"> <b-dropdown-item v-for="colorType in co ...

Bootstrap cards have a fixed width and do not wrap

I've been diving into Django and although I'm fairly new to CSS, I managed to put together a page displaying various products using Bootstrap cards. https://i.sstatic.net/xme5m.png It appears that my code should have wrapped these cards pr ...

Graphs vanish when they are displayed in concealed sections

Looking for a way to toggle between two charts (created with charts.js) by clicking a button? Initially, I had them in separate divs, one hidden and the other visible: <div id="one"> <canvas id="myChart1" width="400" height="400"></can ...

Utilizing a dynamic ref in Vue using the composition API

While working with the composition API in Vue 3, I am trying to create a reference to a component dynamically. Typically, this would involve adding ref="name" to the template and then defining a ref using const name = ref(null). However, I am loo ...

Chat box custom scrollbar always positioned at the bottom

I have a personalized chat box where I included overflow-y for scrolling functionality. However, every time I input a message in the text box, it displays at the top of the scrollbar window. Is there a way to automatically show the most recent message I ...

Techniques for sending a list of objects to a method using AJAX in MVC

Hey there, I am facing an issue with passing a list in an ajax call to my controller as I am getting null data. Below is the code snippet: Class: public class CurrentProcessNameAndBucketName { public string ProcessName { get; set; } public string ...

Updating state based on input from a different component

I am attempting to modify the state of the page index in index.js from the Pagination component, Here is my index.js code: import useSWR from 'swr'; import { useState } from 'react'; const Index = ({ data }) => { const ini ...