steelRat steelRat - 1 month ago 8
Javascript Question

Cant get values from object

I know how that stupid, but i dont understand this simple things.
I have Object, i need get from object names. But don't understand how to get access to inner values.
My object

I try:

data['name']
data[0]
data[0].name


Every time i get this error:


TypeError: Cannot read property


Thanks anyway.

Upd1:

Then i try:


data.constructor


i get this:

Cannot read property 'constructor' of null


I get data from ajax, from this question
When i try:


JSON.parse(data)


I get:


SyntaxError: Unexpected token o in JSON at position 1(…)


That raw data when i get this from server:


{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science
Fiction"},{"id":10770,"name":"TV
Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}

Answer

After reviewing your other question this is your code I'm assuming.

const Main = React.createClass({
    getInitialState : function() {
    return {
      data: null
    };
 },

 componentDidMount: function() {
     var self = this;
     axios.get('https://api')
         .then(function (response) {
            self.setState({data: response.data})
            console.log(response.data);
         })
         .catch(function (error) {
             console.log(error);
         });
        console.log('mount ' + this.state.data );
},
    render() {
        return (
            <h1>{JSON.stringify(this.state.data)}</h1>
        )
    }
})
export default Main;

While you are waiting for the server to come back with the data Main.data equals null. This is why you are getting type of null and if you access data like an array you are getting a type error. You could default Main.data to an empty array while you are waiting for the data to populate.

const Main = React.createClass({
    getInitialState : function() {
    return {
      data: []
    };
 },

As you are using React you will also need to update the component after the data changes. I would suggest looking at this question for that.