Loop through a collection of object arrays within a JavaScript context

Upon loading my HTML page, the following information is displayed:

id: country url: http://data:8004/v1/entity/country name: countries description: All the countries in the world

id: states url: http://data:8004/v1/entity/states name: states data description: A catalog of all data

When clicking on a link, the resulting output is similar to this:

id: edbee2d36f35810d677085f6ec62e7153e96a423fa88b8d5ff2d473de0481e49
url:http://data:8004/v1/entity/county/edbee2d36f35810d677085f6ec62e7153e96a423fa88b8d5ff2d473de0481e49
type: country, 
name: London, 
legal: [object Object]

The data within Legal [{}] is not being returned.

Here is the structure of the JSON data:

[
    {
        "id": "edbee2d36f35810d677085f6ec62e7153e96a423fa88b8d5ff2d473de0481e49",
        "url": "http://data:8004/v1/entity/county/edbee2d36f35810d677085f6ec62e7153e96a423fa88b8d5ff2d473de0481e499",
        "type": "country",
        "name": "London",
        "legal": [
            {
                "type": "attribution",
                "link": "https://en.wikipedia.org/"
            }
        ]
    },

How can I iterate through the nested array to retrieve the legal[{}] content? Additionally, when clicking on a URL result, it displays new results without clearing the previous ones. Even after setting `results.innerHTML=';", the old results aren't cleared before loading new ones.

This is the code snippet in question:


const createElement = (tag, ...content) => {
    const el = document.createElement(tag);
    el.append(...content);
    return el;
  };
  
  const setData = (entity) =>{
      console.log(JSON.stringify(entity))
      let entityProps = Object.keys(entity)
      console.log(entityProps)
  const dl = document.createElement('dl');

  entityProps.forEach(function(prop) {
 
    const pre_id =  document.createElement('pre');

    const dt_id =  document.createElement('dt');
    dt_id.textContent = prop;

    pre_id.appendChild(dt_id);
  
    const dd_id =  document.createElement('dd');
    

    if (prop == "url") {
        const link = document.createElement('a');
        link.textContent = entity[prop];
        link.setAttribute('href', '#')
        link.addEventListener('click',function(e) {
      console.log("I'm working!")
      console.log(e.target.innerHTML)
      RetrieveData(e.target.innerHTML)
  });
  dd_id.appendChild(link);

    } else {
        dd_id.textContent = entity[prop];

    }

    pre_id.appendChild(dd_id);
  
    dl.appendChild(pre_id);

    
  });



  return dl;
  
  }

    const results = document.getElementById("results");


function RetrieveData(url){
   
    fetch(url
    , {
        headers:{
      'x-data': '78shjjhsjja-95ff-a6c0396bd619.b77738aa-f798-4bb9-93c4-914c5c83608c',
      'x-access': 'access-data',
      
    },
})
.then((res) => (res.ok ? res.json() : Promise.reject(res)))
  .then((data) => {
    results.append(
        ...data.flatMap((entry) => [
            setData((entry)),
          document.createElement("br"),
          document.createElement("br"),
        ])
      );
  })
  .catch(console.error);
}


const data=document.getElementById("data");

catalog.addEventListener("onclick",  RetrieveData(`http://data:8004/v1/entity/`));

Answer №1

In your code, you are assigning the value of properties that are not 'url' to be the same as the JS object's value. Here is the relevant section of your code:

 if (prop == "url") {
        const link = document.createElement('a');
        link.textContent = entity[prop];
        link.setAttribute('href', '#')
        link.addEventListener('click',function(e) {
      console.log("I'm working!")
      console.log(e.target.innerHTML)
      RetrieveData(e.target.innerHTML)
  });
  dd_id.appendChild(link);

    } else {
        dd_id.textContent = entity[prop];

    }

You need to handle a special case for the 'legal' property too. You have two options:

  • To use JSON.stringify on the legal property.
  • To process the values within 'legal' similar to how you're handling countries.

An example implementation using JSON.stringify:

 if (prop == "url") {
        const link = document.createElement('a');
        link.textContent = entity[prop];
        link.setAttribute('href', '#')
        link.addEventListener('click',function(e) {
          console.log("I'm working!")
          console.log(e.target.innerHTML)
          RetrieveData(e.target.innerHTML)
        });
        dd_id.appendChild(link);

    } if (prop == "legal") {
        dd_id.textContent = JSON.stringify(entity[prop]);
    }else {
        dd_id.textContent = entity[prop];
    }

If your results are not clearing, it may be due to continuously appending new elements without proper handling, which can be challenging to debug without a testing environment.

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

Error encountered in Firefox: THREE.js throws a TypeError because 'global' is undefined

After attempting to integrate three.js into my code as a standalone script without using webpack, browserify or requirejs, I encountered an issue. My setup involves loading an external Angular app and extending it, but now I need my own version of THREE.js ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

The AJAX request is failing to reach the server

I'm currently using AJAX to populate a dropdown, but for some reason the call isn't reaching the server. Upon checking Firebug, I see the following error: POST 0 status 404 not found This is the code I'm working with: function selec ...

Transferring information from JSON to HTML

Recently, I came across this handy design tool within our service that helps generate Gauge charts by simply adding a specific div class to the desired pages. <div class="gauge" id="g0" data-settings=' { "value": ...

Using conditional logic to render components in VueJS

How can I conditionally display content in a parent component based on a user input variable? If the userinput variable is false, I want to remove the <div class="parent"> and show the PopUp component instead. I've tried using `v-if` ...

Utilizing the index of the .map function in conjunction with internal methods

After running my code, I encountered the following error message: Warning: Encountered two children with the same key, `classroom-1278238`. Keys are required to be unique so that components can maintain their identity during updates. Having non-unique keys ...

Tips for transferring a DotNetObjectReference to a JS DOM event

My goal is to implement JS drag & drop in Blazor, which is working well overall. However, I am facing an issue where I want to set a custom drag image during the ondragstart event. Below is a snippet of my code: <div class="some-draggable-conta ...

Switch the header from left to right movement for mobile devices

I am dealing with two headers in my layout <section> <header class="col-lg-9"> <!-- some content --> </header> <header class="col-lg-3"> <!-- some content --> </header> </section ...

When React object state remains unchanged, the page does not update automatically

i have a state object with checkboxes: const [checkboxarray_final, setCheckboxarray_final] = useState({ 2: ",4,,5,", 9: ",1,", }); i'm working on enabling check/uncheck functionality for multiple checkboxes: these are ...

Carousel position images off-center to the right on smaller screens

I created a fullscreen slider using the carousel bootstrap feature. However, when the screen size shrinks, the background image resizes and centers itself. Instead of centering the image on smaller screens, I want it to focus on the right side. Here is ho ...

JavaScript and HTML are commonly used programming languages for developing

By utilizing JavaScript, I was able to generate a table dynamically based on user input. For example, if the user enters 3 and clicks "go", a table with 3 rows is created. Using the .keyup function allowed me to target a column successfully. However, an i ...

Differences between Cypress and JQuery objects, and the significance of the cy.wrap function

Currently diving into cypress and experimenting with various testing methods. If anyone could lend me a hand with the following inquiries: 1. I've come to understand that most cypress objects utilize jQuery objects for DOM operations, but what sets t ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Unable to shrink array within an object

I'm encountering an issue while trying to reduce an array within an object. The error message I receive is: push is not a function To begin, I initialized my arrays as empty and created an add function to use as the first argument: function add(a,b ...

I am experiencing an issue where the position of the value in the returned response array keeps changing after an Ajax request is made. How can

I am currently using a script that sends an array of numbers through Ajax to a web server. These numbers are then used to query a database, and the corresponding values from the table are sent back. I then display these values in respective divs within my ...

How can I permanently disable a Bootstrap button on the server side using PHP after it has been clicked once?

I am in search of a way to disable a bootstrap button permanently after it has been clicked once. While I am aware of how to achieve this on the client side using JavaScript, the button becomes enabled again after the page is refreshed. I am now looking ...

Tables that respond to changes in screen size, allowing nested table cells to inherit widths

I am currently working on a responsive table with unique content in each row and a concertina feature for expanding rows. When the concertina is activated, it adds another row to the table below the current row, using a td element with a colspan attribute ...

Tips on creating and elegantly showcasing an image from a PDF document on the screen with React-PDF

I am currently working on developing a user interface in JavaScript (React) to enable users to create PDFs directly on the screen. The concept involves having input boxes on one side, which instantly update the fields on the PDF displayed on the other side ...

fill out an HTML form and send it in

When submitting a form with two components, only the first form 'School' and the submit button itself are successfully submitted. The second form 'pool' seems to disappear somehow. <form method='get'> <select nam ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...