Search code examples
javascriptjsonobjectconsole.loglit-element

Can not acess the JSON data inside the object. property


I am currently working on LitElement project. I added JSON data in to the category.items property using this 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();
  }
}

Then I tried to get those data in another component, But I cannot access the Items property.

The code I use to get the data,

handleCategoriesyChanged(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);
    }   

this is the console.log output get in chrome. enter image description here

When I called the object Its show the items property, But i can not access it. So , I tried with the JSON.stringify method and that time not show the items property.I went through the similar question like this in this site,But I can not identify what went wrong and why this happen in this case.


Solution

  • Looks like you are mutating your this.item and add field items somewhere after your logs. This is a reason why there is no key items in your JSON.stringify.

    console.log(this.item); log a reference to this.items and output will be changed when you change object by the reference.

    Try to execute this code and expand first console.log output to see what I'm talking about.

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