Searching for a string within a JSON object in Angular: step-by-step guide

JSON Data Example

{
  "rootData": {
    "test1": {
      "testData0": "Previous information",
      "testData1": "Earlier Information"
    },
    "test2": {
      "testData0": "Partial details",
      "testData1": "Service details"
    },
    "test3": {
      "testData0": "Regular content",
      "testData1": {
        "testData0": "Your customized package"
      }
}
}      
}

Component Script

import  *  as  myData  from  './myData.json';

getData(dataValue: string){    
  console.log(myData.rootData.test1.testData0); //outputs "Previous Information.
    
 return myData.rootData.{{data}}.testData0;
}

The getData method is used repeatedly within a loop with different values like 'test1', 'test2', and 'test3' being passed.

An ideal approach would be to dynamically retrieve data based on the provided key.

Currently, the attempt to use {{data}} is not valid in the JSON object.

The objective is to fetch specific data nested inside the JSON file by utilizing the string value passed to the function.

An alternative solution needs to be explored for achieving the intended functionality.

Answer №1

If you want to retrieve the value associated with a specific key in an Object, you can simply use Object[key] syntax. In this case, key refers to the variable name that holds the key, and using this will give you the corresponding value.

return configData.rootData[data]?.testData0; // Example in Javascript

Instead of utilizing {{ }}, try switching to square brackets for direct access to achieve the desired result.

By examining the code snippet above, rootData[data]?.testData0 is essentially equivalent to

rootData[data] ? rootData[data].testData0 : undefined
. This conditional check is important for validating inputs, especially when dealing with unexpected values for data.

In Typescript:

if (data in configData.rootData && "testData0" in configData.rootData[data]) {
  return configData.rootData[data].testData0;
} else {
  return undefined;
}

const input = {
  "rootData": {
    "test1": {
      "testData0": "Previous data",
      "testData1": "Earlier Data"
    },
    "test2": {
      "testData0": "Partial data",
      "testData1": "Services data"
    },
    "test3": {
      "testData0": "Regular data",
      "testData1": {
        "testData0": "Your package"
      }
    }
  }
};

let data = 'test1';
console.log(input.rootData[data]?.testData0);

data = 'test2';
console.log(input.rootData[data]?.testData0);

data = 'test3';
console.log(input.rootData[data]?.testData0);

data = 'test4';
console.log(input.rootData[data]?.testData0);

data = 'test5';
if (data in input.rootData) {
  console.log('Existed', input.rootData[data].testData0);
} else {
  console.log('Not Existed');
}

Answer №2

I rely on the ng2-search-filter package for filtering in Angular.

One way to utilize it is through a directive:

<tr *ngFor="let data of configData | filter:searchText">
  <td>{{testData0}}</td>
  <td>{{testData1}}</td>
  ...
</tr>

Alternatively, you can apply the filter programmatically like this:

let configDataFiltered = new Ng2SearchPipe().transform(this.configData, searchText);

For a hands-on demonstration, check out this 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

Using AKS Kubernetes to access a Spring Boot application from an Angular frontend using the service name

I have developed two frontend applications using Angular and a backend application using Spring Boot. Both apps are running in the same namespace. I have already set up two services of type Loadbalancer: The frontend service is named frontend-app-lb (exp ...

There was a void in the supertest request with the application/vnd content type

I'm struggling to send a request body using supertest for a post request. Despite configuring body-parser as suggested in other answers, the issue persists. I've checked solutions that mention misconfiguration of body-parser, but they seem to be ...

Splitting code efficiently using TypeScript and Webpack

Exploring the potential of webpack's code splitting feature to create separate bundles for my TypeScript app has been a priority. After scouring the web for solutions, I stumbled upon a possible lead here: https://github.com/TypeStrong/ts-loader/blob/ ...

Is it possible to alter the JSON file being loaded in AngularJS by passing a variable?

I am in need of loading the content from either food1.json or food2.json, and I am attempting to achieve this within the html template: <body ng-controller="MainCtrl" ng-init="init('food1')"> Subsequently, in the JavaScript code: $scop ...

Error when compiling with Component Lab's Autocomplete function for SVG Icons in Material UI

Upon running my project on the browser, I encountered the following error: Error message: ./node_modules/@material-ui/lab/esm/internal/svg-icons/Close.js Attempted import error: 'createSvgIcon' is not exported from '@material-ui/core/utils ...

The error message "Property <property> is not recognized on the type 'jQueryStatic<HTMLElement>'" is indicating an issue with accessing a specific property within the TypeScript codebase that utilizes Angular CLI, NPM,

My Development Environment I am utilizing Angular, Angular CLI, NPM, and Typescript in my web application development. Within one of my components, I require the use of jQuery to initialize a jQuery plugin. In this particular case, the plugin in question ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

Is it possible to make the mat-menu-item the same size as the mat-menu button in Angular Material v.12?

How can I ensure that the mat-menu-item button is the same size as the mat-menu itself? For example, click here <div class="container d-block d-md-none"> <div class="row"> <div class="col d-flex justify-content-cent ...

Conceal the absence of a value within an array

I need assistance with handling an array of parameters: $fields = [ 'idutente' => $_POST['acf']['field_60084ad3970a8'] ?? 0, 'nome' => $_POST['acf']['field_6050d30f14572'], ...

What are the steps to integrate npm into a Cordova app within Visual Studio?

I am currently working on developing a hybrid app using the "Tools for Apache Cordova" project template in Visual Studio. To incorporate angular2 into my project, I have added all the necessary modules to packages.json. After compiling everything and reso ...

"Exploring the power of index signatures and methods in Typescript

What might be the reason for code producing a ts(2411) error? class Greeter { [key: string]: string | number[]; greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hel ...

Creating an object type that includes boolean values, ensuring that at least one of them is true

To ensure both AgeDivisions and EventStyles have at least one true value, I need to create a unique type for each. These are the types: type AgeDivisions = { youth: boolean; middleSchool: boolean; highSchool: boolean; college: boolean; open: bo ...

Extracting information from a JSON response in Swift

[{ "_text" = "turn off the air con"; confidence = "0.609"; entities = { "on_off" = ( { value = off; } ); }; intent = "aircond_temperature"; }] In a JSON response named "outcomes ...

Ionic 3 Local Notification spamming a particular page with excessive pushes

Recently starting out with Ionic, I encountered an issue while developing a basic app that should display a specific page by opening a Local Notification. The problem arises when I create multiple notifications – after clicking on the second notification ...

Error thrown: Unhandled Promise Rejection - The name 'ngForm' could not be exported

Having an issue with ngModel for data binding in my Angular app, getting an error saying ngForm not found. I've already included FormsModule in app.module.ts as shown below. The error disappears when I remove #grantAccessForm= "ngForm", but then the p ...

Understanding the status of file() requests post-executionWould you like the status of file

I am working with an API public function airtime() { $send = file("https://www.example.com/APIQueryV1.aspUserID=CK123& APIKey=456&OrderID=789.............."); if($send) { return $status->ORDER_COMPLE ...

Java Spark API using basic authentication will issue a 401 error response when accessed from an Angular application

My Java Spark API is set up for basic authentication. When I make a call to the URL from Postman with basic auth, it returns a JSON response. However, when I make the same call from an Angular 4 application, I get the error message: "Response for preflight ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

Overriding TypeScript types generated from the GraphQL schema

Currently, I am utilizing the graphql-code-generator to automatically generate TypeScript types from my GraphQL schema. Within GraphQL, it is possible to define custom scalar types that result in specific type mappings, as seen below in the following code ...

Struggling with aligning mat-icon in the center using HTML and CSS?

My issue is that the mat-icon in my generated columns is not center aligned. What could be causing this? When using ngFor to generate my datatable columns dynamically, none of them align correctly. The mat-icon inside my DIV defaults to left alignment. ...