简体   繁体   中英

access array member of type object in javascript

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;

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM