In my code, I created an object with two sub-objects structured like this:
var testObject = {
"page":{
"type": "ePurchase",
"title":"Purchase confirmation"
},
"user": {
"name": "Peter",
"lastname": "Smith"
}
};
What I am trying to achieve is to have an input field in the html page where I can type a property name, such as "name", and then have the program loop through all the attributes of the object to see if there are any matches. My approach is as follows:
var input = document.getElementById('propertyName').value;
for (var i=0; i < Object.keys(testObject).length; i++ ) {
for (var j=0; j < Object.getOwnPropertyNames(testObject[i]).length; j++ ) {
if(testObject[i].getOwnPropertyNames[j] == input) {
console.log("The relevant input value ");
}
}
}
Therefore, if I type "name" in the input field, I expect to receive "Peter" as the output.
However, I encounter the error "Cannot covert undefined or null to object". How can I rectify this issue?
Additionally, given that I am new to JavaScript and programming in general, do you have any suggestions on improving this logic or expressing it more effectively?
Thank you for your assistance in advance! =)