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

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

Tips for utilizing programmatic object keys as TypeScript type?

Consider the object shown below: const obj = { foo: "bar", hello: "world", } and this function for processing objects: const process = (obj) => { const processedObj = {} for (const key in obj) { processedObj[`--${key}`] ...

Converting JSON to parquet format or not converting at all, the choice

We have encountered a situation where converting a JSON file to parquet results in the creation of numerous small parquet files. How can we prevent this from happening? What is the most effective and efficient approach to managing this transformation? Bel ...

Utilize global variables in ng-apimock mocks without the need for double quotes

We integrated ng-apimock into our Angular project and successfully created mock definitions and wrote tests using protractor. Now we are looking to implement global variables in our mock definitions. Here is an example of a mock definition: { "expressi ...

Transforming the primary image to the thumbnail image when hovering over it with JSON objects

Currently, I am facing an issue with my single-page web application project that involves using jQuery, JSON Bootstrap. So far, I have successfully created a category page, product selection page, and item page. The problem arises on the item page where ...

AngularJS: Utilizing Multiple HTTP Requests with the $http Service

Here is the code snippet I am working with: var updateScreen = function() { $http.get("http://localhost:5000").then(function(response){ $scope.numSerie = response.data.refDetail.Num_Serie; $http.get("data/tempsgammes ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

What is the process for bringing data from a REST API into a SQL Server database?

My REST API delivers a JSON-formatted response that looks like this: { "Employees" : [ { "userId":"romin", "jobTitleName":"Developer", "emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_ema ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

Using TypeScript to automatically deduce the output type of a function by analyzing the recursive input type

I am currently working on developing an ORM for a graph database using TypeScript. Specifically, I am focusing on enhancing the "find" method to retrieve a list of a specific entity. The goal is to allow the function to accept a structure detailing the joi ...

Utilizing ConfigurationBuilder to incorporate null values into a list using a json file

As I attempt to insert a list of enums into appsettings.json for later iteration in the code, I encounter an issue. When I include a null value in the list within the JSON file, it does not populate as a null value when loading the Settings from the file. ...

What is the best way to handle rejecting an invalid JSON body when working with Express or Body-Parser?

I'm currently developing an application that strictly accepts a JSON body type. I am utilizing body-parsers and express for this purpose. However, the recurring issue I encounter is that when an invalid JSON body is sent, my program throws back an und ...

Utilizing TypeScript's Type Inference to Simplify Function Combinations

I'm facing a challenge with what should be simple. The types aren't coming through as expected when trying to combine a couple of functions. Is there a way to have TypeScript infer the types without explicitly specifying them? import { pipe, map ...

Is it recommended to utilize JSON in conjunction with jQuery and AJAX within a PHP file?

I've never had the chance to work with json before and honestly, I'm pretty clueless about how it functions. I'm looking to utilize jquery for making ajax calls to a php file. Is it recommended to use json in this scenario? I've heard t ...

Tips for verifying error messages in angular for nested form group fields

Hey there, I'm new to Angular and I'm working on implementing form validations. Below is the code I'm using and encountering an issue with nested form group fields. The error I'm getting in the log is "TypeError: Cannot read property &a ...

`Next.js: Addressing synchronization issues between useMemo and useState`

const initializeProjects = useMemo(() => { const data: ProjectDraft[] = t('whiteLabel.projects', {returnObjects: true}) const modifiedData: ProjectWL[] = data.map((item, index) => { return { ... ...

The JSON object is not providing the length of the array, returning the value as

I'm currently fetching JSON data from a PHP file in the following manner: $.getJSON('fresh_posts.php',function(data){ global_save_json = data.freshcomments; var countPosts = data.freshposts; var howManyPosts = countPosts.length; ...

Using LINQ with ngFor in Angular 6

Within the component.ts, I extract 15 different lookup list values and assign each one to a list, which is then bound to the corresponding <select> element in the HTML. This process functions correctly. Is there a method to streamline this code for ...

Dynamic Mat-select-trigger that automatically adjusts its size to fit the content

Currently, I am experimenting with an Angular Mat-Select that allows multiple selections. To display the selected values in the value field, I have implemented a custom Mat-Select-Trigger. My goal is to enable automatic resizing of the value field (similar ...

What are the distinctions between using getStaticPaths + getStaticProps and useRouter in NextJS?

I'm currently diving into the world of NextJS and finding myself puzzled by the distinctions between getStaticProps & getStaticPaths compared to utilizing useRouter().query. At this point, it appears to me that both methods serve a similar purpos ...