Home > OS >  How to resolve error: "undefined" when reading single values from JSON using JavaScript?
How to resolve error: "undefined" when reading single values from JSON using JavaScript?

Time:11-25

I have a JavaScript function that outputs all values from a JSON file to a Terminal, but when attempting to print a single value, I get the following error: Line 74 - Cannot read properties of undefined (reading 'width')

Here is the code:

var json = `{
    "columns": [{
            "fname": "John",
            "lname": "Doe",
            "age": "23"
        },
        {
            "fname": "Jane",
            "lname": "Doe",
            "age": ""
        },
        {
            "fname": "Tom",
            "lname": "Johns",
            "age": ""
        },
        {
            "fname": "Brian",
            "lname": "Wicks",
            "age": "27"
        },
        {
            "fname": "Tim",
            "lname": "Stone",
            "age": ""
        },
        {
            "fname": "Fred",
            "lname": "Wilson",
            "age": ""
        },
        {
            "fname": "Jason",
            "lname": "Voorhees",
            "age": "90"
        }
    ],
    "rows": [{
        "data": {
            "width": "2",
            "height": "7",
            "length": "",
            "finalresult": "44",
            "firstresult": "",
            "secondresult": "300.00",
            "thirdresult": "700.40"
        }
    }]
}`;


var obj = JSON.parse(json);


function printValues(obj) {
    for(var k in obj) {
        if(obj[k] instanceof Object) {
            printValues(obj[k]);
        } else {
            console.log(obj[k]   "\n");
        };
    }
};

// Printing all the values from the resulting object
printValues(obj);

//print single value
//console.log(obj["columns"]["rows"]["data"]["width"]   "\n"); 
console.log("Print Indiviual values:");
console.log(obj["rows"]["data"]["width"]   "\n"); //The Error

...Could I get some assistance as to what I'm doing wrong? ...Thanks

CodePudding user response:

I see that the width is the property of object data that is inside array rows...

CodePudding user response:

As @Yarin and @codemonkey pointed out—you're trying to access the data object as a direct object property of rows, e.g. obj.rows.data which is wrong and will return undefined because data is not a property of the rows object. Instead it's the first (and only) entry in the array of objects that is rows.

You need to either change the syntax to:

obj.rows[0].data.width

Or take the data object out of the array and remove the array so that the rows object is structured like this:

const obj = {
  rows: {
    data: {
      width: 1
    }
  }
}

// Then you can use this syntax...
console.log( obj.rows.data.width )

// or even this syntax if you really want to...
console.log( obj['rows']['data']['width'] )
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related