What is the method for displaying an array separately for each item in JSON using JavaScript?

The issue arises when using for (let pet of person.pets) loop. In my JSON data, the "pets" field is an array but instead of getting a single array for each object, I am getting all pet arrays for every object in the JSON file. The desired outcome is to have one array per object listed in the JSON example provided below.

{
   "name": "Nallil Keenwillow",
   "age": "32",
   "pets": [
     "Giddo",
     "Berl",
     "Jaenna"
   ]
 },
let persons;
let pets;

async function fetchData() {
  persons = await $.getJSON('persons.json');
  pets = await $.getJSON('pets.json');
  displayPersonsData();
}

function displayPersonsData() {
  for (let person of persons) {
    $('body').append(/*html*/`
    <div class="person">
    <h1>${person.name}</h1>
    <p>Age: ${person.age}</p>
    </div>
  `);
    for (let pet of person.pets) {
      $('.person').append(/*html*/`
      <h2>${pet}</h2>
       `
      )
    }
  }
}

fetchData();

Answer №1

$('.person').append() will add content to all existing .person elements. Make sure you are only appending to the new person element.

function displayPersons() {
  for (let individual of individuals) {
    let personDiv = $( /*html*/ `
    <div class="person">
    <h1>${individual.name}</h1>
    <p>Age: ${individual.age}</p>
    </div>
  `);
    for (let furryFriend of individual.pets) {
      personDiv.append( /*html*/ `
      <h2>${furryFriend}</h2>
       `)
    }
    $('body').append(personDiv);
  }
}

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

Turn off client-side hydration in Nuxt.js or Prevent leaking raw data in Nuxt.js

Working on a Web App built with Nuxt.js for Server-Side Rendering poses some challenges. To safeguard my backend data, I turned to asyncData and Axios for communication with the server. However, Nuxt.js inadvertently exposed my backend data to clients th ...

"Troubleshooting issue with AngularJS ng-repeat order by functionality based on

I am currently trying to sort my ng-repeat by descending date order, with the newest items appearing first. Despite my efforts, I have been unable to achieve this. I have carefully checked for any errors in quoting, but still no luck. I've attempted ...

What is the best way to incorporate tinymce into webpack?

I am facing an issue with integrating tinymce with webpack. It assigns a property called tinymce to window, so one solution is to use the following syntax to require() it (as explained in the bottom of the EXPORTING section of the webpack documentation): ...

Using JQuery to Refresh a Div and Trigger an API Call with a Click Event

Currently, I am working on developing a web application that generates random quotes dynamically. Using JQuery, I can successfully make an API call and retrieve JSON data to display a quote. To allow users to fetch new quotes with the click of a button, I ...

What is the best way to access a variable within the .each() function in jQuery?

One common dilemma often faced is figuring out how to ensure that markup remains accessible within the scope of this .each() function. Instead of focusing solely on resolving this specific issue, my interest lies more in discovering a method to access ext ...

PHP - retrieve a one-dimensional array from a key-value paired array

I have an array that contains different elements, and I need to extract all the values that come before the 'id' key and store them in a separate array. For example: arry('12', '10', '11', '9') [ ...

Checking the validity of subdomain names using JavaScript/jQuery

For users signing up, my form allows them to choose a subdomain for their account. The valid characters allowed in the subdomain are letters, numbers, and dashes. Spaces and most special characters should be filtered out. http://_________.ourapp.com To r ...

I am facing an issue with the clearTimeout function in my JavaScript code. Can anyone help

I am encountering some issues with the clearTimeout() function. The setTimeout() function is working as expected, but I want it to stop running when I close my notification. I'm not sure what is causing the problem in my function. After closing the ...

Developing a MySQL DB-driven Node.js dashboard without the need for a poller

After exploring various StackOverflow posts on the topic, I haven't been able to find a solution that fits my specific situation. We have multiple monitoring instances across our network, each monitoring different environments (such as Nagios, Icinga ...

What improvements can be made to optimize this SQL query and eliminate the need for an additional AND statement at the end

I am working on dynamically constructing a SQL query, such as: "SELECT * FROM TABLE WHERE A = B AND C = D AND E = F" Is there a more efficient way to construct this SQL query without adding an extra AND at the end? Here is my current code snippet: le ...

I find myself struggling to manage my javascript dependencies

Currently, I am utilizing NPM along with various angular packages. As per the tutorial on Basic Grid Part 1 at this link, I am encountering challenges. This is my file directory structure: D:/nodeStuff/uiGrid includes: node_modules uigrid.css uigrid.h ...

Tips on Retrieving JsonResult

I'm encountering some difficulty when trying to write this AJAX function. My goal is to retrieve a JsonResult, which appears to be the most logical solution. However, all of the examples I've come across utilize Json() in order to convert the re ...

Turn off caching for the 'value' event in the Firebase Realtime Database using JS SDK

When setting up a listener for the realtime database : firebaseDb.ref(ref).on('value', (snapshot) => { console.log('snap', snap); const response = snapshot.val(); }); The snapshot is saved for offline use, and upon page refresh, ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...

Enhance Vaadin 14: Automatically adjust TextArea size when window is resized

Using Vaadin 14.1.19 in a project called "My Starter Project," I attempted to create a TextArea that supports multiple lines. Initially, everything seemed fine, but upon resizing the TextArea, it failed to adjust the number of visible lines. Here is the co ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

Use Javascript to deactivate the mouse cursor and rely solely on the keyboard cursor for navigation

I am facing an issue with a div that contains a textarea. The cursor is automatically positioned at the beginning of the text within the textarea. I would like to disable the mouse cursor when hovering over the textarea but still be able to navigate within ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

"Unlocking the Power of Social Interaction with Vue.js

I've successfully integrated a Facebook Login module in my project and it's working well. However, I'm facing difficulties when trying to link the response data with an input field. Can someone guide me on how to achieve this? I'm still ...

Incorporating a jQuery word count and limit within PHP code: a step-by-step guide

I am encountering an issue with a textarea count code. It functions perfectly on its own but when I integrate it as shown below, it stops working without throwing any errors. I have been trying to resolve this for more than 3 days now. Any assistance would ...