Retrieving the JSON information stored within an object

My JSON:

const records = {
"record A": {
    "name": "John",
    "last name": "Doe",
},
"record B": {
    "name": "Jane",
    "last name": "Smith",
},
};

And here is my script:

const obj = {
    logName: function(name) {
        console.log(name)
    },

    displayNames: function(data) {
        for (record in data) {
            let name = record["name"]

            this.logName(name)
        }
    },
};

The output:

undefined
undefined

When I use the following code snippets:

// first example
console.log(records["record A"]["name"])
// output -> John

// second example
for (record in records) {
    console.log(record)
}
// output -> record A
// output -> record B

However, when I try to simplify my code like this:

for (record in records) {
    console.log(record["name"])
}
// output -> undefined
// output -> undefined

How can I access nested JSON data correctly?

Answer №1

The code you've written is correct. Just remember to use for (key in obj) instead of for (value in obj)

const items = {
  "item1": {
    "label": "Label 1",
    "value": "Value 1",
  },
  "item2": {
    "label": "Label 2",
    "value": "Value 2",
  },
};


const data = {
  displayInfo: function(label) {
    console.log(label)
  },

  showLabels: function(items) {
    for (item in items) {
      let label = items[item]["label"]

      this.displayInfo(label)
    }
  },
};

data.showLabels(items);

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

What could be the reason for this Javascript code not functioning as intended, failing to generate a random number between 1 and 3 when I click on any of the buttons

Could someone help me with generating a random number between 1 and 3 each time I click on one of the buttons (rock, paper, scissors)? I am new to programming and not sure what I'm doing wrong. <!doctype html> <html lang="en"> <head& ...

Scala's FOLD method adeptly handles both valid and invalid code blocks alike

In my code snippet below, I am implementing JSON input validation using a controller. The validation process includes JSON schema validation and responses are provided based on whether the input is valid or invalid. However, I encountered an unexpected beh ...

Using AngularJS to retrieve information from a PHP script

As a beginner in AngularJS, I am currently working on retrieving data from a PHP file that interacts with a database and displays the results in JSON format. However, when testing this functionality, I am facing difficulties as it is not displaying any dat ...

How can I connect a JavaScript function with a Bootstrap Text Input Modal?

My webpage contains a basic Bootstrap Modal with a text input field, which I want to display when the "Report A Bug" button is clicked. <div class="btn-group" id="exampleModal" role="group"> <button id="myBtn ...

Real-time Firestore Updates in Vue's Listener

Struggling to set up a Firestore listener for real-time updates? Check out this snippet of code I'm working with: db.collection('users/user') .onSnapshot(function(snapshot) { snapshot.docChanges().forEach(function(change) { ...

How can I troubleshoot my outdated JavaScript tool that is duplicating elements in an array?

Below is the input that needs to be converted into JSON format as shown: {RS0004036}:{0;3}:{0000003AB;0000003BC}_{RS0004036}:{3;3}:{0000003DE;0000003FG}_{RS0004036}:{1;2}:{0000003HI;0000003JK} The code should parse the above input and generate a JSON stri ...

Using JQuery to properly introduce a script in the body of a webpage

<script> /* adjust #splash-bg height based on #meat element */ $(window).on('load',function(){ var splashbgHeight = $("#meat").css("top"); $("#splash-bg").css("height",splashbgHeight); $(w ...

Learn the steps to successfully rotate the custom icon in Material-Ui select without impacting its functionality and making sure it remains clickable

I've been trying to incorporate my own icon for the material UI select component. I successfully replaced the default icon using the "IconComponent" attribute in MU select. However, I'm facing issues with the new icon not rotating when the menu ...

What is the best way to handle this Json string that has been escaped using Gson in Java

So I keep receiving responses like the one below that I can't seem to handle: { "message": "someName someLastName has sent you a question", "parameters": "{\"firstName\":\"someName\",\"lastName\":\"someLastN ...

Troubleshooting issue in Django: 'QueryDict' object does not contain 'read' attribute when working with ajax json object

Currently, I am struggling with parsing a JSON object in my Django view that was sent over by the client using Ajax through the POST method. JavaScript: $.post('/update_vendor_merchandise_types/', JSON.stringify(json_obj)) View: def update_ve ...

There seems to be a mistake in the syntax: The JSX closing tag for <a> on line 17 is missing

Ever since I started working on React.js last week, I took the initiative to provide closing tags for the anchor <a> tag in the code snippet below. function App() { return ( <div className="App"> <table> ...

Invoke a specific URL during an HTML5 upload

So I've got this code that allows for file upload via drag and drop using HTML5 in the browser. $(function(){ var dropbox = $('#dropbox'), message = $('.message', dropbox); dropbox.filedrop({ // Customizing upload settin ...

FIREBASE - ReferenceError: Authorization cannot be accessed until initialized

Currently, I am in the process of learning about Auth with Firebase using NextJS. I have been trying to grasp the concept by referring to multiple sources such as articles and YouTube videos, but I have encountered an error that is hindering my progress. ...

Change the time format from '18/10/2016 10:31:22PM' to '18/10/2016 22:31:22' in JavaScript

var currentDate = new Date('18/10/2016 10:31:22PM'); var formattedTime = currentDate.toLocaleTimeString(); alert(formattedTime); This code is returning an 'invalid date' output. To fix this issue, I need to convert the date format to ...

Sliding down with a delay using jQuery

I'm attempting to create a hidden div that slides down when a button is clicked and then waits for about five seconds before sliding back up. I've experimented with using delay(), but I'm unsure if I'm applying it correctly. Additionall ...

react scroll event not displaying drop shadow

As a newcomer to JavaScript React, I've been attempting to create a feature where the navbar drops a shadow when the user scrolls down. Unfortunately, it's not working as intended. Can anyone point out what I might have done incorrectly? I suspe ...

Three.js: Transparent background for background elements and png particles

I'm struggling with making the background invisible and setting the alpha channel on my particles. I was hoping to use your example script wegl_particles_sprite for the Christmas season. I adjusted it to fit my needs by placing it in a fullscreen div ...

Crafting Effective AngularJS Directives

Recently, I've been delving into AngularJS and have grasped the core concepts quite well. As I embark on building my own application, I find myself struggling with laying out the blueprint, particularly in terms of directive design. Are there any not ...

Angular 2 Error: When used in strict mode functions or arguments objects, the properties 'caller', 'callee', and 'arguments' may cause a TypeError

I'm facing an issue with Angular 2 that seems to be a common problem, but I haven't been able to find a solution yet. I've created a service that is called from another Component, which works fine. The problem arises when I try to make an h ...

What does my HTML code show in the console log for the AJAX data?

Need some help with transferring data using an ajax request. Trying to send the input field contents, but getting unwanted html code in output of console.log("ok" + data), while console.log("ok" + formData) gives the desired value. In my Django view, the ...