Locate the corresponding key for a value within a intricate json dataset

Hello everyone, I am just starting to learn Angular and I have encountered a problem that I need help with. I have a JSON data structure like the one below:

{"Jar1":{"class1":["method1","method2"],
               "class2": ["method2,"method3"]
              },
 "Jar2":{"class3": 
        ["method1","method2"],
 "class4":["method2,"method3]
            }
 }

For example, if my variable is set as classItem="class3", how can I retrieve the value "Jar2" from this JSON? Any assistance would be greatly appreciated. Thank you in advance. Best Regards

Answer №1

If your data is in JSON format and stored as a string, you can easily convert it to an object in JavaScript using the built-in JSON.parse method. In this object, `Jar1` and `Jar2` will represent properties. To find the property that contains the `class3` value, you can iterate through all entries in the object until you locate the desired one. Retrieve all entries of an object with the standard JavaScript method Object.entries, which gives you access to all property names and values within the object. By utilizing the Object.keys method, you can search for keys within the value object to ascertain if the object includes the `class3` property.

Below is an example demonstrating this approach:

const classItem = 'class3';
const parsedJsonObject = JSON.parse(`{
  "Jar1": { "class1": ["method1", "method2"], "class2": ["method2", "method3"] },
  "Jar2": { "class3": ["method1", "method2"], "class4": ["method2", "method3"] }
}`)
const [jarPropertyName, _] = Object.entries(parsedJsonObject).find(([_ ,jarObject]) => Object.keys(jarObject).includes(classItem));
console.log(jarPropertyName);

You can also check out this StackBlitz link for a working example.

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 is the best way to display a Dictionary collection in C#?

I have a problem trying to display an array or collection. The code in my class file is supposed to print the content: //Display All public void Display() { Console.WriteLine(ID + "\t" + Product + "\t" + Category + "\t" + Pr ...

Django - I need to update the dictionary content when a button is clicked

I am trying to create a functionality on my HTML page where a number displayed increases by 1 every time a button is pressed. However, the code I have written so far does not seem to be working properly. Below is the code snippet: mypage.html <form met ...

Exploring Angular 2 MVC for debugging JavaScript

I'm currently troubleshooting my main controller, but I can't seem to find it in the dev tools along with my service. Is there a way for me to debug my JavaScript files without using TypeScript? Below is an image of my project structure which I s ...

Having trouble resolving all parameters for the Router in Angular RC 5 during unit testing

After upgrading to Angular RC 5, I encountered an issue with all components using 'ROUTER_DIRECTIVES'. When attempting to unit test the component, I received the error message 'Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ...

When utilizing the catch function callback in Angular 2 with RxJs, the binding to 'this' can trigger the HTTP request to loop repeatedly

I have developed a method to handle errors resulting from http requests. Here is an example of how it functions: public handleError(err: any, caught: Observable<any>): Observable<any> { //irrelevant code omitted this.logger.debug(err);//e ...

Troubleshooting Promise resolution issue within TestBed.compileComponents in Angular 2 testing

I'm currently in the process of developing a test module for a module within my Angular2 component that utilizes the templateUrl property. As a result, I need to make the TestBed.compileComponents async call to compile before conducting any testing. ...

Implementing simultaneous single ajax requests from multiple components in an Angular 2 CLI project

Imagine a scenario where there is a single service called json-data-service.ts, with a method getWebservicedata() that returns http.post(url), effectively making an ajax call when the method is invoked. On the same page, I have various components such as p ...

"Exploring the concepts of inheritance in Typescript

I'm seeking answers regarding inheritance in TypeScript/JavaScript. Below is my base class (express controller router): abstract class BaseCtrl { abstract model; // Get all getAll = (req, res) => { this.model.find({}, (err, docs) => ...

Exploring the usage of arrays within Angular 4 components. Identifying and addressing overlooked input

I'm struggling with array declaration and string interpolation in Angular 4 using TypeScript. When I define the following classes: export class MyArrayProperty { property1: string; property2: string; } export class MyComponent { @Input() object: ...

Angular 5 is encountering an error with a recursive template, specifically a RangeError stating that the maximum call stack

Hey there, I'm currently utilizing Angular recursive template to represent arrays recursively. The code I've been following is provided in this link. My array is dynamic in nature. <ul> <ng-template #recursiveList let-list> ...

Jackson converts null values in maps to empty strings

Is there a way to configure a global ObjectMapper setting (or any other customization) so that all json Map<String, String> objects are deserialized into maps without null values (replacing them with empty Strings)? For example: class MyClass { M ...

What is the method for accessing the default value of an element by utilizing a placeholder in Protractor?

Is there a way to retrieve the default text in an input field using Angular? <input _ngcontent-c20="" autocomplete="off" type="text" disabled="true" placeholder="Username" class="ng-untouched ng-pristine ng-valid"> The default value inside the in ...

Modify the dropdown menu title dynamically based on the selection made in Angular

My Angular web-application has a dropdown menu that looks like this: <div class="btn-group" dropdown> <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">NAMEOFDROPDOWN <span class="caret"></span>&l ...

What is the reason for Parameters<Func> not being able to extend unknown[] (Array<unknown>) in TypeScript strict mode?

The main point of the title is that I have come across this particular code: type testNoArgsF = () => number; type testArgsF = (arg1: boolean, arg2: string) => number; type unknownArgsF = (...args: unknown[]) => number; type anyArgsF = (. ...

I encountered a TypeError when attempting to load MDX in Next.js with the mdx-js/react library

My Goals and Assumptions for the Project Please note that this question has been translated using Deepl Translations. I aim to integrate mdx-js/react into Next.js for loading mdx files. Environment Details: Operating System: macOS Big Sur Node Version: ...

Updating an Object using Angular's @Input() feature

I am facing an issue with my GameStats Object, which is part of a self-defined interface. When I update the value of an attribute, the child component does not recognize the change. I have tried using ngOnChanges, but it does not get triggered, and ngDoChe ...

insert information into a fixed-size array using JavaScript

I am attempting to use array.push within a for loop in my TypeScript code: var rows = [ { id: '1', category: 'Snow', value: 'Jon', cheapSource: '35', cheapPrice: '35', amazonSource ...

Can the type of a template literal be flipped in any way?

Consider the scenario where we are working with a string that is required to begin with /: type StartsWithSlash = `/${string}` What is the best approach to reverse this type? In other words, how can we modify the type to allow any string as long as the in ...

What is the reason that providers are not automatically optimized for tree shaking?

Why is it that Angular does not automatically remove unused services provided inside a module, unlike how it can tree shake components that are not used? Even when a component is declared inside a module but not utilized anywhere, it will not be included i ...

Endless cycle of invoking Angular 16 function

I am currently facing an issue with my Angular app that uses AWS Amplify. When calling a function upon user authentication, everything works smoothly except for the first time login scenario. After signing in with temporary credentials and updating the pas ...