Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7.

{ "data":[
    {
       "dataId":"Atlanta",
       "parentDataId":"America"
    },
    {
       "dataId":"Newyork",
       "parentDataId":"America"
    },
    {
       "dataId":"Georgia",
       "parentDataId":"Atlanta"
    },
    {
       "dataId":"South",
       "parentDataId":"Atlanta"
    },
    {
       "dataId":"North",
       "parentDataId":"South"
    }
   ]
}

In the above response, the dataID Newyork does not match any of the parentDataIDs in the entire JSON array. I now aim to filter out only the second array with DataID to create a new array.

This validation will be implemented in TypeScript for Angular 7.

The desired output should look like this - showing DataIDs without corresponding parentDataIDs:

[
  {
    "dataId":"Newyork",
    "parentDataId":"America"
  },
  {
     "dataId":"Georgia",
     "parentDataId":"Atlanta"
   },
   {
      "dataId":"North",
      "parentDataId":"South"
     }
]

Any assistance or feedback is greatly appreciated.

Answer №1

To achieve this, you can utilize the filter method:

let filterValue = 'Atlanta';
const filteredResult = data.data.filter(item=> item.parentDataId != filterValue
    && item.dataId != filterValue);

For demonstration purposes, here is an example:

let data = { "data":[
    {
        "dataId":"Atlanta",
        "parentDataId":"America"
    },
    {
        "dataId":"Newyork",
        "parentDataId":"America"
    },
    {
        "dataId":"Georgia",
        "parentDataId":"Atlanta"
    }
   ]
};

let filterValue = 'Atlanta';
const filteredResult = data.data.filter(item=> item.parentDataId != filterValue
    && item.dataId != filterValue);
console.log(filteredResult);

Answer №2

Take a look at this StackBlitz Link

Here is my approach in the code snippet below:

reducedData = [...this.data];

this.data.reduce((c,n,i) => {
   this.data.reduce((d,o, inex) =>  { 
      if ( n.dataId === o.parentDataId){ 
           this.reducedData.splice(i,1, {'dataId': 'removed', parentDataId: 'true'}); 
      } else {
         return o;
      }
    },{});
   return n;
}, {});   

this.reducedData = this.reducedData.filter (value => value.dataId !== 'removed');

The HTML file section:

<h4> If dataId does not have parentId </h4>
<hr>
<pre>
  {{reducedData | json}}
</pre>

MODIFY

If you do not want to utilize an additional object like reducedData, here is another solution that can be used effectively. Check out this StackBlitz Link

Within the component.ts file:

this.data.reduce((c,n,i) => {
    this.data.reduce((d,o, inex) =>  { 
      if ( n.dataId === o.parentDataId) {
      this.data[i]['removed'] = "removed";
      } else{
        return o;
      }
    },{});
   return n;
}, {});

this.data = this.data.filter (value => value['removed'] !== 'removed');

In the component.html file:

<h4> If dataId does not have parentId </h4>
<hr>
<pre>
 {{data |json}}
</pre>

Answer №3

Here's an example for you to follow.

const info = { "info":[
    {
       "id":"Los Angeles",
       "parentID":"California"
    },
    {
       "id":"San Francisco",
       "parentID":"California"
    },
    {
       "id":"Silicon Valley",
       "parentID":"San Jose"
    }
   ]
};

const searchKey = "San Francisco"
const matchFound = info.info.some( item => item.parentID ===  searchKey && item.id === searchKey)
let relevantItems ;
if(!matchFound){
    relevantItems = info.info.find(item => item.id === searchKey )
}

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

Error encountered in amCharts Serial Chart when data parsing is enabled with the setting "parseDates": true which resulted in the failure to display data

Using Spring as a webservice, I received a JSON response with stock data: [ { "date": "2016-04-17", "open": 1085.0, "high": 1092.2, "low": 1072.0, "close": 1088.3, "volume": 54100, "value": 1088.3 }, { "date": "2016-04-14", "open": 1081. ...

The angular httpTestingController.expectOne method throws an error, even when the httpClient's get method has

I have an issue with my testing in Angular. I am trying to test a simple function within a service: getReports(url: string): Observable<Report[]> { return this.http.get<Report[]>(url); } This is the test that I have written: it(`should c ...

Troubleshooting Date Errors in Typescript with VueJS

Encountering a peculiar issue with Typescript while attempting to instantiate a new Date object. <template> <div> Testing Date</div> </template> <script lang="ts"> import Vue from "vue"; export default Vue.extend({ name: ...

Exploring the functionality of anchor tags in Angular: what makes them tick?

After recently diving into Angular development, I've come across a curious issue: anchor tags seem to be malfunctioning when clicking on the text inside. Here is the code snippet in question: <a href="{{ downloadAddress }}"><i class="fa fa- ...

aligning JSON information with JavaScript object

I am currently in the process of setting up a sample dataset in JSON format for a JavaScript tutorial that I'm going through. Here's how the data object looks in JavaScript: app.Book = Backbone.Model.extend({ defaults: { coverImage: ...

Ionic 2 - Dynamically Loading Segments

I am dealing with categories and dishes. Each dish is associated with a specific category. My goal is to send an http request to retrieve all the dishes belonging to a particular category. This will result in an array like: { Soup[{'Name',&ap ...

Using Generic Types in TypeScript Files for React Components

I have encountered an issue that I haven't been able to find a solution for online. When I define a function in a ts file like this: const lastGeneric = <T>(arr: Array<T>): T => { return arr[arr.length - 1]; } But when I try to do ...

The @JsonIgnore annotation in Jax-RS does not seem to be functioning properly after including the service endpoint in the Application

I recently embarked on the journey of developing my first REST API and managed to get it up and running for a brief moment. The core of my API involves an Entity class called User that is linked to another database table named Bookmark. To prevent this ref ...

The functionality of Laravel's IlluminateHttpJsonResponse::json method is not available in every situation, as it is only applicable in certain

In my application, there is a controller method that interacts with an external API and returns the result. The flow of this controller method is as follows: ControllerY -> getDataFromExternalAPI() This controller method gets called in two different wa ...

Utilizing the get and set methods to alter the structure of a string, but encountering the issue where the set method is

Upon receiving a datetime through an HTTP request, I need to format it before utilizing it. To achieve this, I utilize the get and set methods in my code. However, I noticed that the set method is never invoked. This is how my component (AdminComponent) l ...

method for retrieving a single key-value pair from a JSON object

Suppose I receive a JSON object from the server using var oSer = new JavascriptSerializer(); var sJson = oSer.Serialize(myObject); The JSON returned to the client through an AJAX call is: "{\"IsValid\":false,\"EmployeeId\":null,&bsol ...

Ways to resolve a 404 error on a live Angular application being hosted by NGINX

I am encountering an issue with my deployed application on a server where every time I refresh a specific page, I receive a NGINX 404 error. The application is running within Docker. Below is the configuration file for NGINX. server { listen 80; locat ...

Is there a way to dynamically change an icon based on certain conditions using typescript?

I am struggling with displaying icons in my TypeScript code using Material Icons. I need to dynamically change the icon based on a condition, for example if the power is false I want to display 'power_off', but if it's true then I want to di ...

How can we integrate information from a local JSON file onto our website?

My role is with a small publishing company that has an internal website featuring a static HTML table showcasing our published products. We are looking to dynamically list and sort our products (with about 1-2 items published daily) based on data from an ...

Script execution in '<URL>' has been prevented due to sandboxing of the document's frame and the absence of the 'allow-scripts' permission setting

When I deploy my pure Angular application with a REST API to a production server and try to access its URL from another site (such as a link in an email), I encounter a strange problem. Firefox doesn't provide any error message, but Chrome says: Blo ...

Ignoring the validation pattern for a string within an array in Json Schema

My schema is defined as follows: "permissions": { "type": "array", "properties": { "items": { "$ref": "#/definitions/p ...

Trouble accessing contacts on LinkedIn

When attempting to retrieve the LinkedIn connections for a logged-in user, I used the following API Request: However, I encountered an error message: { "errorCode": 0, "message": "Access to connections denied", "requestId": "OFP0JOLOHO", "status" ...

The Angular Router is continuing to show the HomeComponent upon navigation, rather than just displaying the ChildComponent

Lately, I've been diving into Angular and attempting to create a github search application using the github api. However, I've encountered some roadblocks with routing and data passing. My goal is for the user to land on a page like /user/userID ...

Having trouble with the .d.ts module for images?

I'm relatively new to Typescript and the only thing that's giving me trouble is the tsconfig.json. My issue revolves around importing images (in Reactjs) and them not being found: client/app/Reports/View.tsx:11:30 - error TS2307: Cannot find mod ...

Revitalize access token with Keycloak in Javascript

I am currently working with keycloak-js version 8.0.1 and have a function called getToken that checks if the token is expired. If it is expired, the function refreshes it; otherwise, it returns the current token. The issue I am facing is that even though t ...