0

I have been trying to access array member from an Array (data_array).My variable data_array is part of json something similar to code below. The code below is not the actual code. The actual code is coming in play when i am trying to create a React component. I can paste the complete React component but it would contain some unnecessary information. So i thought i would add some mock example. Apologies if it misled people. Currently i was hoping to get some hints on what could possibly go wrong in such scenario? :

data: {
    "name": "Arjun",
    "records" : [
      {
        "value": 3
      },
      {
        "value": 6
      },
      {
        "value":7
      }
    ]
  }
   var data_array = data.records

   console.log(data_array) -> Array[3]
   console.log(data_array[0]) -> It displays Uncaught TypeError: Cannot read property '0' of undefined
   console.log(typeof data_array) -> Object. 

What's confusing to me is my first output as it says its an Array.I am fairly new to javascript. So maybe i am missing something. Any help would be appreciated.

Edit: This would still be missing a nested React Component but it would be of no use in this case. I am calling the nested component Foo for now


var React = require('react'),
  Router = require('react-router'),
  mui = require('material-ui'),
  Foo = require('./foo.jsx');


var TempReact = React.createClass({
  mixins: [Router.Navigation],

  getInitialState: function() {
    return {
      data: {}
    };
  },

  componentDidMount: function() {
    // Do a web request here to actually get the data from the backend API
    // this.setState({

    // });

    // For now, load our fake data
    this._loadFakeData();
  },

  render: function() {
    //console.log(this.state.data)
    for(var record in this.state.data.records) {
      console.log(record.Value);
    }
    //console.log(this.state.data["records"][0]["Value"])
    return (
      <div>

        <p>^ That will still say , since the header up there is decided by temp-page.jsx, which is
          based on the route</p>

        <br/>
        <p>We've loaded the fake data into our component's state, and here's proof:</p>
        {this.state.data.name}
        <br/>
        <br/>

        <Foo name={["temp1",this.state.data.records,"green"]}/>

      </div>
    );
  },

  _loadFakeData: function() {
    this.setState({
    data: {
        "name": "Arjun",

        "records" : [
          {
            "Value": 6
          },
          {
            "Value": 7
          },
          {
            "Value": 8
          }
        ]
      }
    });
  }

});

module.exports = TempReact;
7
  • 1
    Can you post a demo to reproduce the issue? Commented Mar 23, 2016 at 19:49
  • 2
    Can't reproduce -> jsfiddle.net/sqjxnp1k Commented Mar 23, 2016 at 19:50
  • Thanks for such a quick reply. I can try but this part of a React component. So i will try to write something. This is the gist of the issue. Commented Mar 23, 2016 at 19:51
  • Is this your actual code? why the colon data: {}? Did you mean to set that with an assignment operator var data = {} Commented Mar 23, 2016 at 19:51
  • No this is not a actual code (this was just a quick mock up of an issue). I am facing an issue when i am trying to do something similar in a React Component. I am new to JS . So forgive me for writing something wrong Commented Mar 23, 2016 at 19:54

4 Answers 4

3

Arrays are typeof Object. They're just an object with some fancy stuff going on.

The following example works:

var data = {
"name": "Arjun",
"records" : [
    {
        "value": 3
    },
    {
        "value": 6
    },
    {
        "value":7
    }
  ]
}
var data_array = data.records
console.log(data_array[0]) // Object {value: 3}

This error happens when you do something like this:

var data = {};
var data_array = data.array; // data.array is undefined and subsequently data_array.
console.log(data_array[0]); // Throws: Uncaught TypeError: Cannot read property '0' of undefined
Sign up to request clarification or add additional context in comments.

2 Comments

Hi. Thanks for the reply. i would not be expecting an error. when i try to access an element. Again this would not the actual code. I think i should take it down and re write the actual code. I was trying to get an answer on what could go wrong which would lead to an error when you access an element
Oh I see, yeah I would edit it with your actual code. I will also update my answer to explain a bit better :)
0

You're not far off lets say you store this object in a variable called jsonData just for an example :

var jsonData = {
  data: {
    "name": "Arjun",
    "records" : [
      {
        "value": 3
      },
      {
        "value": 6
      },
      {
        "value":7
      }
    ]
  }

}

You'll need to access the variable > property > nested property , then specify the index like so :

var data_array = jsonData.data;
   console.log(data_array.records[0].value)

--> should log 3

EXAMPLE HERE: http://codepen.io/theConstructor/pen/wGdpjq

1 Comment

exactly but why is it not working when i am doing in that React Component?? That is my question primarily. But i am getting a lot of flake for asking it in the wrong way :(
0

So the problem might have been with SetState() in React, I was able to access the objects by pushing them first in an empty array:

var varArr = new Array();
for(key in this.state.data.records) {
   if(this.state.data.records.hasOwnProperty(key)) {
       var value = this.state.data.records[key];
       varArr.push(value);
   }
 }

Comments

-1

data_array is an Array. data.records in an Array. What are you expecting to see?

1 Comment

Hi. Thanks for the reply. i would not be expecting an error. when i try to access an element. Again this would not the actual code. I think i should take it down and re write the actual code. I was trying to get an answer on what could go wrong which would lead to an error when you access an element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.