0

This is the problem

enter image description here

This is the script

var data = [];

axios.get('https://jsonplaceholder.typicode.com/posts')
    .then(function (response) {
        data.push(response.data['0'])
    })
    .catch(function (error) {
        console.log(error);
    });
console.log(data);
console.log(data['0'].body); //this is where I get the error

As you can see in the picture it should be correct but why I cannot read the property ?

2 Answers2

0

Are you sure the data object is filled when you try access it?

Does the following work?

var data = [];

axios.get('https://jsonplaceholder.typicode.com/posts')
    .then(function (response) {
        data.push(response.data['0'])
        console.log(data['0'].body);
    })
    .catch(function (error) {
        console.log(error);
    });
Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80
-1

Your data is an array, so it must be accessed with integer like data[0].body.

String accessor might be useful for Object type, not array. For example, you can also do data[0][“body”].

Joshua Stephen
  • 196
  • 1
  • 8