Navigating through nested objects in JSON can be achieved by accessing the key of the

I'm struggling with a JSON file. I have a main object that contains nested objects, but I can't seem to access them.

"vendors": {
"1": {
  "id": 1,
  "name": "Exponential Interactive, Inc d/b/a VDX.tv",
  "policyUrl": "https://vdx.tv/privacy/",
},
"2": {
  "id": 2,
  "name": "Captify Technologies Limited",
  "policyUrl": "https://www.captify.co.uk/privacy-policy-opt/",
},
"4": {
  "id": 4,
  "name": "Roq.ad Inc.",
  "policyUrl": "https://www.roq.ad/privacy-policy",
},

I am trying to access the "name" property and display it in a li tag. Here is my current code:

fetch("jsonpage")
  .then((res) => res.json())
  .then((data) => {
    for (const number of Object.keys(data.vendors)) {
      let newVendor = document.createElement("li");
      newVendor.textContent = number;
      ulList.appendChild(newVendor);
    }
  })
  .catch(console.error);

However, I am only able to access the numbers "1", "2", and "4", and I'm not sure what to do next.

Answer №1

To retrieve the object using its key, use the following method.

Object.keys(data.vendors).forEach((key) => {
  console.log(data.vendors[key]);
  console.log(data.vendors[key].name);
})

Answer №2

I don't have the exact code available, but I think this approach might be effective. Utilize the number as an index for the array of vendors:

fetch("jsonpage")
  .then((res) => res.json())
  .then((data) => {
    for (const num of Object.keys(data.vendors)) {
      let newVendor = document.createElement("li");
      newVendor.textContent = data.vendors[num].name;
      ulList.appendChild(newVendor);
    }
  })
  .catch(console.error);

Answer №3

To iterate through the data.vendors object, you can use a for in loop.

const data = {
  vendors: {
    '1': {
      id: 1,
      name: 'Exponential Interactive, Inc d/b/a VDX.tv',
      policyUrl: 'https://vdx.tv/privacy/',
    },
    '2': {
      id: 2,
      name: 'Captify Technologies Limited',
      policyUrl: 'https://www.captify.co.uk/privacy-policy-opt/',
    },
    '4': {
      id: 4,
      name: 'Roq.ad Inc.',
      policyUrl: 'https://www.roq.ad/privacy-policy',
    },
  },
};

for (const key in data.vendors) {
  console.log("ID:", data.vendors[key].id)
  console.log("Name:", data.vendors[key].name)
  console.log("Policy URL:", data.vendors[key].policyUrl)
}

Answer №4

Here is a suggestion for you to consider:

fetch("jsonpage")
  .then((res) => res.json())
  .then((data) => {
    for (const number of Object.keys(data.vendors)) {
      let newVendor = document.createElement("li");
      newVendor.textContent = number;
      ulList.appendChild(newVendor);
      //Next, we can retrieve additional information;
      let name = data.vendors[number]['name']
      let policyurl = data.vendors[number]['policyUrl']
    }
  })
  .catch(console.error);

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

Begin the process of setting up PDF.js on the website

I've been attempting to incorporate PDF.js into my website, but I'm struggling to do it correctly. When I try to display the PDF file on the screen, I encounter this issue: https://i.sstatic.net/aixrP.png Although I can't see the PDF file ...

Retrieve information from a form in AngularJS without relying on two-way data binding

Utilizing two-way data binding, the code operates effectively. However, there is a stipulation - instead of using =, use <. Upon the initial launch of the application, the text inputs will contain predefined values. The objective is to enable users to ...

The use of jQuery's ajax() function to retrieve JSON data from a URL is resulting in a response that is

I am facing an issue where the data object received in my complete() callback is not a JSON object, but rather an [Object object]. Despite this, I can still see a string of my JSON response in data.responseText. Below is my jQuery .ajax request: $.ajax({ ...

Limiting functional component re-renders to only occur when certain states change

Is there a way to make a component re-render only when a specific state in that component changes, instead of re-rendering with every state change? Here is an example code snippet: suppose I have a component with three states and I want it to re-render on ...

Running a JavaScript function within a designated div element

I'm currently facing an issue with executing a javascript function - onload only in a specific div. I seem to be stuck on this problem, so if anyone could offer some assistance, I would greatly appreciate it. Thank you very much in advance! functio ...

Having difficulty sending data to a controller through AJAX in Code Igniter. Can anyone help troubleshoot

I recently started learning PHP OOP and am currently using the Code Igniter framework. I encountered some difficulties in sending data to the controller using AJAX, so I attempted a simple test to check if AJAX was functioning properly, but unfortunately, ...

I cannot seem to locate the System.Json.DLL file

I've been testing out some JSON examples with the Http Client, but they mention a System.Json.DLL that I can't seem to locate. Check out this resource for more information on System.Json.DLL, but it's not showing up in my installed files. Co ...

Filling in a text field with the text content (rather than the value) from a dropdown menu

Presently, I have the select box with the id "title" populating a text field with the id "costcenter". The current code works perfectly fine when using the VALUE of the select box to trigger the population of the cost center field. However, my requirement ...

The error "500 window is not defined in Nuxt3 when using the composition API"

Is it possible to detect the user's preference for color scheme and set a data-mode attribute on the document root (html)? I've been struggling with this. In my app.vue code, I have the following: <template> <div> <NuxtLayout /> ...

Issue with ExtJs 4 Grid panel resizing incorrectly when window is resized

I have a Grid Panel rendered in a DIV without specifying any width for either the DIV or the Grid Panel. I want them to take up all available browser width, but the Grid does not resize itself when the browser window is resized by the user. I have tried va ...

A guide to navigating through arrays and retrieving key values in PHP

I need help with iterating over an array that contains a decoded JSON string. My goal is to create separate variables for first name, last name, etc., and then display them in individual rows within a table. Below is an example of the array structure. Si ...

Nested arrays in the JavaScript programming language

Is this JavaScript code accurate: var options = []; options.push(["Tom","Smith"]); options.push(["Mary","Jones"]); where each item in options is a two-element array of strings. I plan to add items to options using a for loop. Furthermore, can I i ...

Parsing error: 'Unexpected token' found in JSON while attempting to access an external file

Currently working on implementing backbone for a new project along with underscore, requirejs, jquery, and bootstrap. Things are progressing smoothly as I aim to include static survey question data into one of the data models. { "defaultOptions": { ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

html5sql - Struggling to establish a connection with my database

I recently started using html5sql.com for my html5 DB needs and I must say, it's a fantastic module! However, I've hit a roadblock. In my index.html/index.js file, I have set up my database and created tables in it. try { html5sql.open ...

Creating JSON output with Jersey 1.6 using JAXB

@XmlRootElement public class Task { private String description = "example"; public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } ...

Entering numerous numerical values across a variety of input fields

My website currently has a form with 6 input fields where visitors need to enter a 6 digit code. To make it easier for them, I want to allow users to simply paste the code we provide into the first input field and have the remaining digits automatically po ...

Error encountered with the $get method of AngularJS Provider during configuration() function

Recently, I configured a Provider that fetches a language JSON file from a web server and delivers it to Angular within the config() method. Here is the provider setup: .provider('language', function () { var languageWsURL , languageC ...

Angular's routeProvider is failing to load the next template

I am struggling to implement a feature where each item in a list has a button that, when clicked, uses $routeProvider to navigate to a specific template. However, I keep encountering 404 errors when trying to access the page through the link. Any guidance ...

JavaScript's GET request fails to include form data in the URL

Express Router Module for Book Details Form Page <form class="container col-md-5 signupform bg-white my-4 py-3 formShadow" method="GET" action="/admin/addBook/add" , onsubmit="return validate()"& ...