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

The function with which you are trying to use 'new' does not have a call or construct signature

How can I prevent the error from appearing in my console.log? An error message - 'Cannot use 'new' with an expression whose type lacks a call or construct signature.' - keeps popping up. var audioContext = new window.AudioContext() ...

How can I arrange a table in Angular by the value of a specific cell?

Here's the current layout of my table: Status Draft Pending Complete I'm looking for a way to sort these rows based on their values. The code snippet I've been using only allows sorting by clicking on the status header: onCh ...

What is the purpose of exporting both a class and a namespace under the same name?

While exploring some code, I came across a situation where a class and a namespace with identical names were exported from a module. It seems like the person who wrote this code knew what they were doing, but it raised some questions for me. Could you shed ...

Encountering a warning during the installation of Angular CLI

As a newcomer to this platform, I recently installed Node.js. However, when attempting to execute the command npm install -g @angular/cli, an error was encountered: **npm WARN deprecated [email protected]: Legacy versions of mkdirp are no longer supported ...

Exploring the potential of utilizing records within deepstream.io

Lately, I've been delving into the world of records and I find myself pondering on the practical limitations when it comes to the size of a json structure. Is there a recommended maximum length? Can you store an entire chat history as an (anonymous) r ...

`Developing data-driven applications with MVC3 using object binding`

Currently, I am facing a challenge with my project that involves using Entity Framework. To provide context on the database model: public class AssetType{ public ICollection<Field> Fields { get; set; } } public class Field{ public int Id {g ...

The 'ObjectID' property is not present in the 'CollectionStatic' data type

Encountering an issue with the MongoDB npm module: mongoId = new Mongo.Collection.ObjectID()._str; Attached is a screenshot for reference. Appreciate any assistance. ...

What is the best way to ensure that two promises are both resolved before triggering a function from within a promise?

In my code, I have a forEach loop on a matches fetch that looks like this: matches => { matches.forEach(match => { Promise.all([this.teamService.getTeam(match._links.homeTeam.href)]) .then(team => { match. ...

What sets apart ajax calls from getJSON requests?

I am encountering an issue with my Web.API app being served from the URL http://server/application. When I try to pull data from the servers using a GET request on the client side, I am facing unexpected behavior. The following code snippet works as expec ...

Tips for understanding the encoding of an NSString in UTF-8

Currently, I'm utilizing SBJSONParser for parsing a JSON data retrieved from an API. In the fetched JSON data, the title is displayed as title = "F\U00c3\U00b6rdermittel";, which is already UTF-8 encoded by SBJSONParser. Ideally, the string ...

Gatsby, in combination with TSC, does not properly transpile the rest operator

I'm attempting to integrate TypeScript with Gatsby following the guidelines provided here. However, I am encountering an issue where the tsc command is failing to transpile the spread (...) operator and producing the error shown below: WAIT Compili ...

Is there a way to access and read all JSON files within a directory in a Meteor application?

Is there a way to read all JSON files within a folder in my Meteor application? This is the structure I currently have: /server -- /methods -- -- file1.json -- -- file2.json I've attempted to read all JSON files using this code snippet: var ...

Sharing markdown content between two Vue.js components

I have a markdown editor in View A which is displaying the result in the current View. My goal is to share this result with another page, View B. In View A, there is a button that allows the user to share the markdown result with View B. I am using a texta ...

Convert JSON data into an HTML table using JavaScript without displaying the final result

I need help troubleshooting my JavaScript code that is supposed to populate an HTML table with data from a JSON file. However, the table remains empty and I can't figure out why. Sample JSON Data [{"User_Name":"John Doe","score":"10","team":"1"}, { ...

Typescript Syntax for Inferring Types based on kind

I'm struggling to write proper TypeScript syntax for strict type inference in the following scenarios: Ensuring that the compiler correctly reports any missing switch/case options Confirming that the returned value matches the input kind by type typ ...

Is there a way to properly structure the json data displayed in my network tab on Chrome?

After sending an http request to my backend, I received a json response in the network tab. However, the format of the json is unreadable. To clarify, here is a screenshot: https://i.stack.imgur.com/RBiTd.png Currently using Chrome, I am seeking assistanc ...

The AJAX data did not successfully render the jQuery template

When I manually input the JSON string, the code below works perfectly. However, when I try to pass the JSON string returned from an AJAX call to render the template, it does not function as expected. Can someone assist me in identifying the issue? functio ...

Developing an Android application that utilizes PHP to return JSON encoded data

I have a situation where I am outputting JSON encoded data at the end of a PHP file on my server using the code "echo json_encode($response);" When this PHP file is accessed directly from a browser, the encoded data appears in the browser instead of being ...

The FirebaseX Ionic native plugin received 2 arguments instead of the expected 3-4

Trying to implement Firebase Phone Auth with the FirebaseX plugin, I encountered an issue. Here is the code snippet I used: async getVerificationCode(): void { const res:any = await this.firebaseX.verifyPhoneNumber('+16505553434', 60); ...

Utilizing Google BigQuery's nested JSON functionality within Power BI

While attempting a connection to Google BigQuery using Power BI native connector, I encountered an issue where nested fields were being displayed without their corresponding column names. To address this problem, I diligently followed the guidelines provi ...