When you try to access the properties of a nested JSON object, the result might be undefined

var validCoins = {
      "nickel": {
        "weight": 5.00,
        "diameter": 21.21,
        "thickness": 1.95,
        "value": 0.05
      },
      "dime": {
        "weight": 2.27,
        "diameter": 17.91,
        "thickness": 1.35,
        "value": 0.10
      },
      "quarter": {
        "weight": 5.67,
        "diameter": 24.26,
        "thickness": 1.75,
        "value": 0.25
      }
    };

Approach 1:

Object.keys(validCoins).forEach(function(coinType) {
      alert(coinType.weight);
}

Technique 2:

for (var key in validCoins){
//Checking for hasOwnpProperty here doesn't make a difference
        alert(key["weight"]);
    }

Neither of these techniques seems to be working as expected, returning undefined values. What could be the issue? Do I need to include any libraries or dependencies? My objective is to achieve this using vanilla JavaScript.

Answer №1

const coinDetails = {
      "penny": {
        "weight": 2.50,
        "diameter": 19.05,
        "thickness": 1.52,
        "value": 0.01
      },
      "nickel": {
        "weight": 5.00,
        "diameter": 21.21,
        "thickness": 1.95,
        "value": 0.05
      },
      "dime": {
        "weight": 2.27,
        "diameter": 17.91,
        "thickness": 1.35,
        "value": 0.10
      }
    };

for (let coin in coinDetails) {
  if (coinDetails.hasOwnProperty(coin)) {
    console.log(coinDetails[coin].thickness);
  }
}

Code Playground

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

Tips for utilizing the REST service through ajax(jQuery) in a Spring Boot application

Currently, I'm referencing an official Spring document regarding this particular topic It seems like there might be something missing or omitted because despite my efforts with Intellij and SpringBoot, I can't seem to get it to work. My impleme ...

NodeJS hit with ECONNREFUSED error while trying to run localhost server

I currently have a NodeJS server running on my local machine, listening to port 50000. I am trying to make a simple GET request to this server from another local server, but I keep receiving an ECONNREFUSED error message: { Error: connect ECONNREFUSED 127 ...

Unraveling the attributes of a JsonObject recursively: A guide

I'm currently working on parsing strings into JSON objects and I am in need of a way to recursively iterate through the attributes within these objects. My goal is to create a function that can effectively traverse through the object's attributes ...

Intersecting Rays and Positioning Spheres with three.js

I have a scenario where ray intersection is functioning properly with tube geometry. Upon ray intersection, a small red sphere and a tooltip appear next to the cursor. The image below shows the scene without a header: When I include a header using a div e ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

Stopping React from re-rendering a component when only a specific part of the state changes

Is there a way to prevent unnecessary re-renders in React when only part of the state changes? The issue I'm facing is that whenever I hover over a marker, a popup opens or closes, causing all markers to re-render even though 'myState' rema ...

Display a progress bar that shows completion based on the maximum value supplied

I successfully created a progress bar using HTML, CSS, and Javascript. It functions perfectly up to a provided value of 100. However, if a value higher than 100 is given, the progress completes but the value continues to change until it reaches the maximum ...

Using a combination of stringify, regular expressions, and parsing to manipulate objects

As I review code for a significant pull request from a new developer, I notice their unconventional approach to editing javascript objects. They utilize JSON.stringify(), followed by string.replace() on the resulting string to make updates to both keys a ...

Tips for handling alternate lines with two distinct styles in the Ace editor

I am looking to develop a unique note-taking editor using Ace. For instance, if I paste some Spanish text into the editor, I would like to add English words as notes for corresponding Spanish words. My goal is to display these English words above the resp ...

Whenever I try to utilize the "ng-list" in JavaScript, I encounter issues accessing the variable model

HTML <input type="text" ng-list ng-model="OtherHobby" />{{OtherHobby}} <br /> {{AllHobbys}} Javascript $scope.OtherHobby = []; $scope.AllHobbys = $scope.OtherHobby; I ran a test on this piece of code. The variable "OtherHobby" w ...

invoking a controller using a method in JavaScript

As I work on constructing a website using MVC 3 razor, there is a specific scenario that I am currently dealing with: One of the challenges involves a controller method: public ActionResult MyControllerMethod(int parameter){ ''perform some ...

What is an effective method for coordinating JQuery animations simultaneously?

My current understanding of $("#someElement").animate() is that it will run asynchronously in relation to other JavaScript statements. For example: $("#anotherElement").css("display", "none"); $("#someElement").animate(); //The CSS display may change a ...

Executing a python script from an html page by providing it with a string input

I've been searching everywhere for a solution to this problem, but I've only been able to find information on either the python side or the javascript side, and I really need both. Currently, I have a python script that I execute in the command ...

Tips for preserving the URL of a 404 page in AngularJS

We are currently developing an angularjs application where users can publish their profiles as resumes. For example, a valid URL for a published profile would be: www.page.com/public/johnsmith However, if the URL is something like: www.page.com/public/ ...

"Encountered an error: File or directory not found while attempting to export a function

src/test.js module.exports.test = function() { const { readFileSync } = require('fs'); console.log(readFileSync('test.txt', 'utf8').toString()) } index.js const { test } = require('./src/test.js'); test(); ...

What is the best way to use CSS in ReactJS to insert an image into a specific area or shape?

Currently, I'm working on developing a team picker tool specifically for Overwatch. The layout consists of cards arranged horizontally on a website, all appearing as blank gray placeholders. These cards are positioned using the JSX code snippet shown ...

jQuery Problem: Iterating over each element and executing a function

Currently facing an issue with running a function through .each in jQuery. It doesn't seem to be selecting the element properly using 'this'. Here is the code: (Edit: I am trying to center elements absolutely regardless of screen width, for ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Utilizing the map function to modify the attributes of objects within an array

I have a data structure with unique IDs and corresponding status keys. My goal is to count how many times each status repeats itself. Here's an example of my data structure: const items = { id: 2, status_a: 1, status_b: 1, status_c: 3 }; Below is the ...

Can you explain the significance of the $ symbol in the context of this jQuery function?

How are the two functions different in terms of jQuery usage? Question: What is the significance of $ in this example? JS: jQuery(document).ready(function() { console.log('loaded'); }); jQuery(document).ready(function($) { console.lo ...