Exploring nested objects in Javascript through iterating and extracting all properties in a continuous loop (Updated)

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! =)

Answer №1

It appears that the objects are being used incorrectly at inappropriate times.

Please review the console logs provided below:

var sampleObject = {
  "page": {
    "type": "eCommerce",
    "title": "Order confirmation"
  },
  "user": {
    "name": "John",
    "lastname": "Doe"
  }
};


var searchItem = "John" // document.getElementById('propertyName').value;
var properties = Object.keys(sampleObject);
for (var x = 0; x < properties.length; x++) {
  console.log(properties[x])
  var propNames = Object.getOwnPropertyNames(sampleObject[properties[x]])
  console.log(propNames)
  for (var y = 0; y < propNames.length; y++) {
    console.log(searchItem,propNames[y],sampleObject[properties[x]][propNames[y]])
    if (sampleObject[properties[x]][propNames[y]] == searchItem) {
      console.log("Match found");
    }
  }
}

Answer №2

Give this a shot

for (var index=0; index < Object.keys(dataObject).length; index++ ) {
var testObj = Object.keys(dataObject[Object.keys(dataObject)[index]])
       for (var k=0; k <testObj.length; k++ ) {
          if(testObj[k]== user_input) { 
             console.log("Record found");
          } 
       } 
   }

Answer №3

Exploring the for..in StatementThe for...in statement allows us to iterate over the enumerable properties of an object, following its original insertion order. For each property, we can execute specific statements.

var testObject = {
        "page": {
            "type": "ePurchase",
            "title": "Purchase confirmation"
        },
        "user": {
            "name": "Peter",
            "lastname": "Smith"
        }
    };
    for (var outerObj in testObject) {
        for (var innerObj in testObject[outerObj]) {
            if (testObject[outerObj][innerObj] === "Smith") { // document.getElementById('propertyName').value;
                console.log("Record matched");
            }
        }
    }

Let's delve into understanding JSON notation and objects in JavaScript. An object comprises key-value pairs within a JSON structure, allowing access to both keys and values when using a 'for..in' loop. In this scenario, testObject represents a JavaScript object. By iterating over it with 'for..in', we retrieve keys like outerObj which correspond to values, themselves being objects. This enables further nested iterations with innerObj, providing insights into the values linked to these keys. I hope this explanation clarifies the concept for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring information to the server with JSON in the Codeigniter framework

I have a JavaScript array (unitdata_set) that I need to send to the server for database processing using Codeigniter. JavaScript Array (unitdata_set):- [{"unit_id":"13","unit_title":"Testsdsdf","unit_max_occupancy":"3","unit_no":"1","unit_no_adults":"1", ...

Ways to retrieve the child number using JavaScript or PHP

Is there a way to retrieve the child number upon clicking? View screenshot For example, when I click on the X button, I want to remove that specific element. However, this action should only apply to item n2. In order to achieve this, I need to determine ...

Error: Unable to set reference. The initial argument includes an undefined value in the 'gender' property of 'Users.ji8A7TkSldfdvieDqGxko9eV3Jy1'

I followed along with a Firebase Web Tutorial on YouTube about adding data to Firebase Database for an account settings tutorial. However, when I tried to implement the code provided, it didn't work. Can anyone offer any assistance? // Code snippet fo ...

Discovering the worth of an array property in JavaScript

I have a custom script that generates and outputs a JSON formatted object: function test() { autoscaling.describeAutoScalingGroups(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.lo ...

Error code 405 (METHOD NOT ALLOWED) is received when attempting to make a post request to an API

Struggling to develop a basic front end that can communicate with my API. The API functions properly as I am able to retrieve and send data using the POSTMAN client. Fetching data from the server and displaying it on the frontend works fine, but encounteri ...

When attempting to make a post using Prisma's ORM, users may encounter an error message indicating that the post function

Creating a basic prisma application using express and node to query a local mysql database. Encountering an error when calling await prisa.list.create(), details provided below. Here is the script.js code snippet from the HTML page: addItemForm.addEvent ...

Is React failing to identify parameters?

working on my react project, I have an App component which is responsible for rendering multiple child components. Here's how it looks: App render() { return ( //JSX inside <BrowserRouter> <div> <Heade ...

What is the process for setting default parameters using a recompose, lifecycle HOC?

I've created a custom recompose, lifecycle HOC: import { lifecycle } from 'recompose'; export function myHoc(title) { return lifecycle({ componentDidMount() { console.log(title) } }); } export default my ...

Quasar - Optimize for varied platforms

Currently, I am endeavoring to set up a project with various environments including staging, production, testing, and development. When using Vuejs, this task is quite straightforward. vue-cli-service build --mode staging Additionally, I need to create a ...

Is it possible to add a personalized parameter to an unnamed JavaScript replace function?

I am looking to customize a date value in the following format: var d = new Date(); myobj.format(d, "dddd (ddd) S dd'd'.MM (MMM MMMM).yyyy HH:mm:ss.fff t tt T TT (o) {Z}"); I prefer not to utilize date.js because of its large size. The issue ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

Associating an event with a newly created element in Angular2

I'm looking to add a new row with just one click on the + button. This new row will come equipped with a - button that can then be used to delete the newly created row. However, I've encountered an issue in attaching a click event to this new - b ...

The event "subscriptionRemoved" is not being triggered when a password change is made on the Microsoft Graph API

Utilizing the Microsoft Graph API, I have set up subscriptions to receive notifications for calendar events through Node.js. As per the guidelines outlined in the documentation on Enhancing notification reliability for Outlook resources (preview), it speci ...

How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using ...

What is the best way to retrieve a complete DynamoDB scan response using aws-sdk-js-v3 without object types included in the marshaled response?

After struggling with the AWS JS SDK V3 documentation and examples, I decided to share my findings to help others. The official SDK docs were frustrating and misleading, especially when it came to showing marshaled output properly. While the DDB Doc client ...

Encountering an issue with Meteor and node-celery: "Unable to access property 'slice' of null"

Check out the Github repository for reproducing this issue Run localhost:3000 to replicate the problem. In my setup with Meteor 1.4.4.1, I am utilizing the node-celery npm packages on the server side. Upon Meteor initialization, the client automatically i ...

Achieving JSON element sorting in the most effective way

https://i.stack.imgur.com/NQbdN.png Each array contains the following information: {{ id: 39, treaty_number: "qwe", insurant_name: "222", belonging_to_the_holding_company: "test", date_start: "2016-04-15", etc }} Is there a way to sort each array in asc ...

activate the bootstrap popover by double-clicking instead of a single click

Clicking on a certain div triggers a popover to display another div, which works initially. However, once the popover is removed by clicking outside the div, it requires two clicks to trigger the popover again. How can this be fixed so that it always works ...

Implementing a function to specify size limits

As a newcomer to the world of JavaScript, I am facing a particular challenge. My goal is to add a conditional statement in my code that will only execute on screen sizes larger than 768px. $(window).on('scroll', function () { if ($(window ...

Tips for creating dynamic alerts using mui v5 Snackbar

My goal is to call an API and perform several actions. After each action, I want to display the response in a Snackbar or alert. Despite iterating through the messages in a map, I'm only able to show the first response and none of the others. Here is ...