0

I have created the following function

        var jsonData = <?php echo $jsondata; ?>;                            
    var objectLength = <?php echo $lines; ?>; /*length of the object*/
    var dataArray = [];
    var objectParser = {};  
    objectParser.getArrays = function(jsonData, dataType) {
        var i = 0;                          
        stringName = dataType;      
        for (i = 0; i<=objectLength; i++) {
            dataArray.push(jsonData[i].stringName);                 
        }
        return dataArray; 
    }

    var timeStamp = objectParser.getArrays(jsonData,'timestamp');

    console.log(timeStamp);

to take in JSON data and read the data from it. My problem is that right now I am getting a

Uncaught TypeError: Cannot read property 'stringName' of undefined  

in the code which I am not sure why it's happening. Doing

console.log(jsonData[0].timestamp) works just fine

Here is the json data sample [{ "timestamp": "12\/16\/2013 0:00", "curr_property": "7211", "curr_property_cost": "123", "day_property": "48", "day_property_cost": "281", "curr_solar_generating": "4958", "curr_solar_export": "0", "day_solar_generated": "33", "day_solar_export": "0", "curr_chan1": "1964", "curr_chan2": "4958", "curr_chan3": "289", "day_chan1": "13", "day_chan2": "33", "day_chan3": "1" }, ..........]

2 Answers 2

3

Use Bracket Notation

jsonData[i][stringName]

instead of

jsonData[i].stringName

Although suggest that jsonData[i] undefined. Your way to access the property is incorrect

EDIT

Also be careful with the condition i<=objectLength, Make sure objectLength is <= jsonData.length

Sign up to request clarification or add additional context in comments.

Comments

1

Cannot read property 'stringName' of undefined means that the previous operation gave an undefined value instead of an object.

The operation that comes right before .stringName is jsonData[i], so this menas that i points to an index that doesn't exist in the JSON.

This is probably due to your loop, which goes from 0 to objectLength included. I would change that.

Also, @Satpal's answer applies too.

3 Comments

datatype of objectLength is set to number and console.log(jsonData[somerandomno].timestamp) also works. What could be the problem ?
@Bazinga777 One of the problems is that your upper index limit is included (≤), the other is an incorrect usage of object property access. Again, read our two answers.
Thanks, the problem was with the upper limit of the objectlength.

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.