Can Angular be used to dynamically filter a JSON object to display only the fields that match a specified filter text?

Sorry if this question has already been asked; I couldn't find the solution.

Here is my issue:

In my Angular app, I am retrieving a complex JSON object from a web service. I then present this JSON object to the user in tree format using ngx json viewer.

Considering that the tree is extensive and intricate, I would like to allow users to filter which fields they see in the view.

I've been struggling to determine how to filter the fields from the JSON based on the filter text entered in the input box. While I know it's possible to query and filter for specific field values, I haven't come across a way to filter based on the field names themselves.

For example, if I have this JSON:

{
    "firstname": "John",
    "lastname": "Smith",
    "phone": "999-999-9999",
    "address": "123 Main St"
}

And the user types in "name" as the filter text, I want to display only the matching fields:

{
    "firstname": "John",
    "lastname": "Smith"
}

Does this concept make sense? Is it feasible?

Thanks for your help!

Answer №1

Object.keys(o).filter(o=>o.includes("name"))

This code snippet will return the keys in the object 'o' that contain the string "name", but it will not include the corresponding values for those keys.

var o = {
    "firstname": "John",
    "lastname": "Smith",
    "phone": "999-999-9999",
    "address": "123 Main St"};

var matchingKeys = Object.keys(o).filter(o=>o.includes("name"));
var filteredObject = {};

matchingKeys.forEach(key => filteredObject[key] = o[key]);

After running this script, the 'filteredObject' will only contain the keys and values where the key contains the string "name" like so:

{
    "firstname": "John",
    "lastname": "Smith"
}

If you want to use this as a TypeScript function, you can define it like below:


public filterObjectContainsKey(a_sFilterKey: string, a_oObject: Object): Object {

    var matchingKeys = Object.keys(a_oObject).filter(o=>o.includes(a_sFilterKey));
    var filteredObject = {};

    matchingKeys.forEach(key => filteredObject[key] = a_oObject[key]);
    return filteredObject;
}

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

In Deno, it is possible to confirm that a variable is an instance of a String

I'm having trouble asserting instances of string in Deno: import { assertInstanceOf } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2642405050405e445e59445e">[email protected]</a& ...

Unable to locate 'reflect-metadata' module within Docker container on Production Server

I encountered an error: module.js:550 throw err; ^ Error: Cannot find module 'reflect-metadata' at Function.Module._resolveFilename (module.js:548:15) at Function.Module._load (module.js:475:25) at Module.require ( ...

Moshi was anticipating an object to start but instead encountered an array at the beginning - custom converter was

My current setup involves using Moshi for converting Retrofit responses into objects. However, I've encountered a specific issue where the conversion fails and an exception is thrown: com.squareup.moshi.JsonDataException: Expected BEGIN_OBJECT but was ...

Navigating through the nested object values of an Axios request's response can be achieved in React JS by using the proper

I am attempting to extract the category_name from my project_category object within the Axios response of my project. This is a singular record, so I do not need to map through an array, but rather access the entire object stored in my state. Here is an ex ...

While the AWS CodePipeline is executing the script, an error is appearing in the log. Please address this issue and resolve it

This is the content of buildspec.yml: version: 0.2 phases: install: commands: - npm install -g typescript pre_build: commands: - echo Installing source NPM dependencies... - npm install build: commands: - echo Bui ...

The issue arises in React when input elements fail to render correctly following a change in value, specifically when the keys remain identical

Click here to view the code sandbox showcasing the issue The code sandbox demonstrates two versions - a working one where Math.random() is used as the key, and a not working one where the index of the array is used as the key. When the array this.state.v ...

Exploring possibilities within nested JSON objects

I have a large JSON object. A fragment of it looks like this: data = [ { 'make': 'dacia', 'model': 'x', 'version': 'A', 'typ': 'sedan', 'infos': [ ...

Issue with fetching data from the last ID in PHP MySQL database

I have been working on developing an API in PHP to retrieve data from my database and display it on an Android app using JSON. My goal is to initially display 20 records in the app, and then load another set of 20 records each time the user scrolls to the ...

When transforming the Google Cloud output to JSON with Protobuf, certain fields may be left blank or without a value

After using Google Cloud Natural Language API to convert message output into json with protobuf, the sentiment and magnitude fields are unexpectedly empty. Printing them separately reveals their values. How can this issue be resolved? Both json_results = M ...

Merge attributes from objects within an array

I am seeking assistance with a basic task in TypeScript as a newcomer to the language. My challenge involves manipulating an array of objects like this: // Sample data let boop = [ {a: 5, b: 10}, {a: 7, c: 8}, {a: 6, b: 7, c: 9} ]; My objectiv ...

Exploring the extracted data from a JSON file in text format

When making a JSON request to a server, I require access to a time-stamp that will adjust dynamically based on another time variable. Using the requests module, I am sending a post request with the JSON as a .txt file. Here is my JSON data. My goal is to ...

Observable not triggering Subject.next() as expected

service.ts constructor() { this.cartUpdate = new BehaviorSubject<Array<AppCartItem>>([]); // this.cartUpdate.subscribe((items) => { // #### 1 // console.log('Service Items : ', items); // }); } add(item) : Obser ...

Constant Struct Key in Golang

When working with PHP, we often encounter situations like: if ($env == "dev") define("key", "key") else define("key", "secret") // json ouput //{ key : "value" } or { secret : "value" } How can this PHP approach be effectively translated to GO? My ...

Locate elements within an array where a specific attribute includes the specified search term

While working with Javascript, I encountered an issue where the function I wrote to retrieve objects from an array was not returning all the data that met the query criteria. In my dataset, which originally contained 1536 objects, there are several jokes ...

Loading an Angular 2 application or component through an HTTP request can be done by following

Is there a way to dynamically load an Angular2 application or component from a remote server using HTTP? For example: Template: <app-local></app-local> <app-http></app-http> Sample code for AppComponent of app-local: [...] load ...

There are missing dependencies for the designated entry point, "@vcd/ui-components."

Upon running the application with npm start from the branch named ryan-a11y-merge-to-master at https://github.com/juanmendes/vmware-cloud-director-ui-components, I encountered the following error. However, when I switch to the master branch, no errors are ...

Transforming JSON date format to a different one using Jackson libraries

My spring boot 1.3.5 application is using jackson with the dependency "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.5.0". Encountering an issue when a user inputs a date value in a format different than expected (mm/dd/yyyy) during a POST requ ...

Collaborate on Typescript Interfaces within a Firebase development environment

I've been developing a Firebase project using Angular for the frontend, and incorporating the @angular/fire library. Within this project, I have created multiple interfaces that utilize firebase and firestore types. For example: export interface ...

When retrieving data from a JSON file, only display the value instead of showing the entire

When a user tries to login, I have created a modal window. If the user enters incorrect credentials, it returns SignInStatus.Failure, which is fine. However, the page then refreshes and only displays the number "3" at the top of the page with no other cont ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...