Unable to retrieve the JSON data located within the object's property

I am currently working on a LitElement project and have successfully added JSON data to the category.items property using the following code:

fetchItems(category) {   
    if (!category || category.items) {
      return;
    }

    this.getResource({
      url: 'data/' + category.name + '.json',
      onLoad(e) {
        category.items = JSON.parse(e.target.responseText);
      },

    });
}

 getResource(rq) {
    let xhr = new XMLHttpRequest();
    xhr.addEventListener('load', rq.onLoad.bind(this));
    xhr.open('GET', rq.url);
    xhr.send();
  }
}

However, I encountered an issue when trying to access the Items property in another component.

The code snippet I used to retrieve the data is as follows:

handleCategoriesChanged(e) {
    this.categories = e.detail.categories.value; 
    if(this.location != undefined){
        for(let i=0; i < this.categories.length; i++){
            if(this.location.params[0] == this.categories[i].name){
                this.item = this.categories[i];
            }
        }
        console.log(this.item);
        console.log(this.item.items);
        console.log(JSON.stringify(this.item, null, 2));
        console.log(this.item.items);
    }   

When checking the console.log output in Chrome, I noticed that although the object was being called and the items property was visible, I was unable to access it directly. I attempted using the JSON.stringify method as well, but still couldn't access the items property. I searched for similar issues on this site, but couldn't figure out what went wrong in my case.

Answer №1

Seems like there is a mutation occurring on the this.item object, causing the addition of the items field after the logs are generated. As a result, the key items is not present in the JSON.stringify output.

When you use console.log(this.item);, you are essentially logging a reference to this.items, which means the output will change if you modify the object using that reference.

To understand this better, try running the following code and check the first console.log output after expanding it:

var object = {};
console.log(object);
console.log(object.a);
object.a = 'first key';
console.log(object);

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

Is the API providing a response in the form of an HTML document

I just created a cutting-edge React application that leverages the power of "fetch" to fetch data from an API. Within my App component in the "App.js" file, you can find the following code snippet: function fetchData() { fetch(`WORKINGURLWITHAPIKEY`) ...

React component not displaying dynamic content when extending from a class

Hey guys, I'm a newbie when it comes to React and I've encountered a problem with loading content fetched from an API. Usually, I use export default function About({ posts }) which works like a charm in loading my content. However, for one specif ...

Ajax Form Submission

My query relates to a combobox I have integrated: <select id='addOPTION' onchange='fillADDid(this.value);'> <option value=0>Select</option> <option value=1>etc</option> <option value=2>etc</option ...

"Learn how to eliminate both the key and value from a dictionary within a list in Python when the value is either NaN, null,

What is the correct way to remove both key and value from a dictionary list in Python if the value is null, nan, or empty? I have attempted to do so using the code below, but it does not work. Is there a mistake in the code? We want to remove the key-valu ...

Error in Internet Explorer when attempting to close a Fancybox iframe that plays a YouTube video

Even the FancyApps page itself contains the error mentioned below. If you visit using Internet Explorer 9, for example, follow these steps: Go to Internet Options > Advanced > Disable script debugging (Internet Explorer). Then click on the YouTube ( ...

What is the most effective way to organize an array according to a key function that is computationally intensive?

After posting this question regarding sorting an array with a key function, it became evident that utilizing a comparison function was inevitable. The challenge at hand includes: Having a resource-intensive key function that needs to be transformed into ...

The button component in my React application is not functioning as expected, despite utilizing the useState and useEffect hooks

I'm having trouble with my Button not working, even though I am using useState and useEffect Check out the code below: import React, { useState, useEffect } from "react"; // import Timeout from "await-timeout"; import ...

Access model information from a controller with the help of Next.js and Sequelize

I'm currently working on a project involving Vue.js as my frontend and Next.js as my backend. While everything seems to be running smoothly, I am facing an issue with retrieving my model data back to my controller... Additional details: I have utili ...

Utilize the power of AJAX and Laravel to seamlessly upload an Excel file

I am currently facing an issue with importing an Excel file using AJAX and Laravel in my application. The form of excel import is embedded within another form and I have observed that the error handling is not displaying the error messages correctly on the ...

What are some strategies for efficiently displaying a large amount of data on a screen using Javascript and HTML without sacrificing performance?

Imagine having a hefty 520 page book with over 6,200 lines of text ranging from 5 to 300 characters each. The challenge lies in efficiently displaying this content on the screen for users to read without causing lag or performance issues. Attempting to re ...

I'm looking for ways to incorporate TypeScript definition files (.d.ts) into my AngularJS application without using the reference path. Can anyone provide

I'm interested in leveraging .d.ts files for enhanced intellisense while coding in JavaScript with VScode. Take, for instance, a scenario where I have an Angular JS file called comments.js. Within comments.js, I aim to access the type definitions prov ...

What is the best way to execute a script on the homepage just one time?

I need some assistance with a script that should only run when a visitor arrives at my site for the first time. I want all content to be hidden initially and then revealed in a visually appealing way when the visitor clicks a button. However, I do not want ...

"Troubleshooting: State array in ReactJS/NextJS not rendering correctly following setState

I am facing challenges with rendering my objects using .map() within React / NextJS. Within my code, I have a function where I retrieve images from Firebase Cloud Storage as shown below: getImages = () => { let firebase = loadFirebase() ...

Angular nested lists with drag and drop functionality

Recently, I've been working on creating a drag and drop dashboard and stumbled upon an amazing nested list at this link. This particular implementation uses the AngularJs JavaScript framework. However, since I don't have much experience with it, ...

Pass the ActiveRecord object retrieved in the success of the ajax call in Rails as a parameter to another subsequent

Imagine this scenario: I have a view named "Dashboard" featuring a basic form and a button labeled "Draw Graphs". The goal is to trigger two ajax requests upon clicking the button, fetching the required data from the database for creating two distinct grap ...

Retrieve a specific portion of a deeply nested JSON object and display only the key-value pairs that pique my interest within that subset

I possess a deeply embedded json file: My goal is to extract and analyze only the subset I am interested in, specifically all content within the 'node' key. How can I achieve this? Extract the subset of this json file that contains "edges ...

Is there a way to efficiently fetch localStorage data upon launching a React application and seamlessly store it in Redux using the useEffect hook without experiencing any data loss issues?

Should I avoid mixing React hooks and mapStateToProps in my application and instead use Redux hooks like useSelector? In my React app, I have an array of 'friend' data stored in Redux. Using useEffect in one of my components, I am saving this da ...

Altering iframe Content with the Help of Selenium Web Driver

I am looking to update the content of an iframe with new material using Selenium WebDriver. Note: I have attempted the following method: driver.swithTo().frame(frame_webelement); driver.findElement(By.xxx).sendKeys("Mycontent"); While I was able to cle ...

PHP problem with parsing JSON

I received a json response that looks like this {"success":true,"results":[{"response":["random1"],"id":"6566","Limit":1},{"response":["random2"],"id":"6563","Limit":1},{"response":["random3"],"id":"6568","Limit":1}]} My goal is to extract random1, rand ...

What is the most efficient way to retrieve the operating system's name and version using JavaScript?

I'm in the process of developing an object that will simplify accessing browser and system information by implementing a function. One particular function within this object is responsible for retrieving the operating system name and version, returnin ...