0

I'm a ReactJS and axios newbie.

I want to iterate and extract json data if the key is number (like 0, 1, 2....) and don't know how can I write this piece of code. (because the server provide the json dynamically, and we don't know how many elements it will have)

Now I can extract the data with key = 0 (assume there exists this element)

class ContentBody extends Component {
    constructor(props) {
        super(props);
        this.state = {
            jdata: []
        }
    }
    componentDidMount() {
        var self = this;
        // read data periodically
        setInterval(function() {
            axios.get(URL)
                .then(function(response) {
                    self.setState({
                        jdata: response.data[0].Name
                    });
                })
                .catch(function(e) {
                    console.log("ERROR ", e);
                })
        }, 1000);
    }
}

// below is json data from the server
{
  "0": {
    "Assigned": false, 
    "Name": "BebopDrone-Test001.", 
    "droneID": 0
  }, 
  "1": {
    "Assigned": false, 
    "Name": "BebopDrone-B046836", 
    "droneID": 1
  }, 
  "2": {
    "Assigned": false, 
    "Name": "BebopDrone-Test002.", 
    "droneID": 2
  }, 
  "function": "getAllDroneStatus()"
}


// my pseudo code might be 
for(int i = 0; i < jsonObject.size(); i++){
    if(key is number){
        extract corresponding value
    }
 }
Wen Chen
  • 13
  • 1
  • 6

2 Answers2

1

Your response is an Object not an Array.

You can't access an object using array indexing.

Assuming response.data is the body of your json, you should access your object properties like this: response.data['0'], response.data['1'], response.data['2']

You can iterate over an object using for..in.

Your data model (aside from the reference to 'getAllDroneStatus()') suggests that an array might be more useful.

{
   "jdata" : [
      {
         "Assigned": false, 
         "Name": "BebopDrone-Test001.", 
         "droneID": 0
      }
    // ... 
    ]
}

Then you can iterate, reduce, filter and so on.

1

The response that you get from the server is an object, what you should do is loop over the Object and then update data in state where I assume you only need name

componentDidMount() {
    var self = this;
    // read data periodically
    setInterval(function() {
        axios.get(URL)
            .then(function(response) {
                var names=[];
                Object.keys(response.data).forEach(function(data) {
                     names.push(data.Name);
                })
                self.setState({
                    jdata: names
                });
            })
            .catch(function(e) {
                console.log("ERROR ", e);
            })
    }, 1000);
} 
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400