Accessing a property that does not exist under the type 'string' - how to iterate through nested JSON objects

I am currently working on iterating over nested objects and storing the outer object key along with the inner nested object values in arrays. My goal is to use this data to display them in a group bar chart using chart.js.

let goodArray = [];
let notgoodArray = [];
let fruitsArray =[];

const obj = {
 "oranges": {
    "good": 1,
    "not_good": 0
 },
 "apples": {
     "good": 1,
     "not_good": 0
 },
 "grapes": {
     "good": 2,
     "not_good": 0
 }
}

I have managed to store the outer object keys like this

for (var key in this.obj) {
  fruitArray.push(key);
}

This results in the fruit array looking like this

['oranges', 'apples', 'grapes']

However, I am unable to access the properties of the fruit objects within this loop. I tried adding code like this

for (var key in this.obj) {
  goodArray.push(key.good);
  notgoodArray.push(key.not_good);
  fruitArray.push(keyname);
}

But this resulted in an error message saying

"Property 'good' does not exist on type 'string'"

My aim is to have an array for the 'good' values like

[1, 1, 2]

and another array for the 'not_good' values like

[0, 0, 0]

Answer №1

To retrieve the object information, you should follow these steps:

for (let property in this.obj) {
  goodValues.push(this.obj[property].good);
  notGoodValues.push(this.obj[property].not_good);
  fruitNames.push(property);
}

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

Using socket.io-client in Angular 4: A Step-by-Step Guide

I am attempting to establish a connection between my server side, which is PHP Laravel with Echo WebSocket, and Angular 4. I have attempted to use both ng2-socket-io via npm and laravel-echo via npm, but unfortunately neither were successful. If anyone h ...

Having trouble with Heroku deployment? Unsure of the correct way to deploy your Angular App + NodeJs?

Here's a recent log using heroku logs --tail I'm facing some issues and not sure what's wrong :( 2019-07-23T14:46:07.163085+00:00 app[api]: Release v1 created by user ************************* 2019-07-23T14:46:07.163085+00:00 app[api]: Ini ...

Tips for creating a universal event listener for keyPress events in Angular 5

This question pertains to the Angular 5 framework. Despite extensive research on topics like ElementRef and EventEmitter, I have been unable to find a straightforward method to programmatically trigger a global "Document scope" keyPress or keyDown event s ...

What is the reason behind taps in TypeScript only registering the first tap event?

One issue I am encountering is that only the first tap works when clicked, and subsequent taps result in an error message: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') Here is the code I am using: https://codepen ...

What is the best method for accessing Blob data in Deno?

Currently, I am attempting to read from a websocket within Deno. Below is the code snippet (please note that you will require an API key from AISstream for it to function properly) /** * URL used by the API; this might change if the version changes or at ...

Using the -t or --testNamePattern in Jest will execute all tests

Currently, I have set up my testing framework using jest and ts-jest based on the guidelines provided by the ts-jest documentation. When I execute the command yarn test --listTests, I can identify the specific test file I intend to run: processNewUser.ts ...

Tips on ensuring a certain HTML tag is used in the component interface

I developed a custom checkbox component that can receive children props from its parent interface CustomCheckboxProps { children?: string; } const CustomCheckbox = (props: CustomCheckboxProps) => { const { children } = props; return ( <di ...

Creating a custom function with event handling and piping in Node.js

I am currently in the process of developing a Node.js library using TypeScript. The primary purpose of this library is to facilitate downloading content from a specified URL. I envision it being utilized in the following manner: import customLibrary from ...

Add the phrase "choose an option" to a dropdown menu and then reset the dropdown in Angular

I need to implement a dropdown that initially displays a blank option such as "select an option", and when the user chooses an item from the dropdown, this initial field should disappear. Also, I want to automatically clear the selected option after a cert ...

What is the proper way to specify the type for a <video> element reference in React when utilizing Typescript?

I have been experimenting with controlling the play/pause state of a video in React.js using ref's. My code functions correctly but I am encountering tslint errors that I am currently trying to diagnose: function App() { const playVideo = (event:a ...

Navigating State as a Fresh Path in Ionic Framework using Angular UI-Router

I am currently using the Ionic Framework along with its AngularJS UI-Router and $stateProvider to manage different views within my application. However, I am facing challenges in specifying to the $stateProvider that I have multiple "Main Views", each of ...

Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates? array = [ {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'} ]; The desired output is: result = [{id: ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

Typescript's dynamic arguments feature allows for passing varying numbers of parameters without using ell

// Defining function: lm( vv: number, kk: string[] ) { console.log( kk ) } // Invoking the function this.lm( 33, ["dd","ff","da"] ) I have thoroughly tested the provided code and it is working flawlessly. But why do we need ellipses? Refe ...

What could be causing the errors I'm encountering in my TypeScript component within AngularJS?

I am working with an AngularJS component written in TypeScript called news.component.ts. This component makes a call to a service named google.service.ts in order to fetch news RSS using a service that converts XML to JSON. Within the NewsComponent, I hav ...

`The utilization of a collective interface/data type within an Angular application`

I created a HeaderComponent that requires an object with the structure of {title: string, short_desc: string} as its input property. @Component({ selector: 'header', templateUrl: './header.component.html', styleUrls: ['./hea ...

Guide to TypeScript, RxJS, web development, and NodeJS: A comprehensive manual

Looking for recommendations on advanced web development books that focus on modern techniques. Digital resources are great, but there's something special about reading from a physical book. I don't need basic intros or overviews - consider me an ...

Jaydata is a powerful open source library for interacting with databases

I rely on jaysvcutil for compiling OData $metadata and generating JayDataContext.js, which is truly impressive. However, I prefer to work with Typescript without using import/export syntax or other third-party tools like requirejs or systemjs. Even thoug ...

Deciding between bundling a Typescript package and using tsc: When is each approach the best choice

When it comes to publishing a Typescript NPM package (library, not client), I have two main options: 1. Leveraging Typescript's compiler First option is to use the Typescript compiler: tsc and configure a tsconfig.json file with an outDir setting: { ...

Is using $timeout still considered the most efficient method for waiting on an Angular directive template to load?

When it comes to waiting for a directive's template to render, our team has been following the approach of enclosing our DOM manipulation code in a $timeout within the directive's link function. This method was commonly used in the past, but I&ap ...