Search code examples
jsonangulartypescriptfilterangular7

How to get filtered the array in json reponse based on condition check with keys in angular 7


I would like to get filterd the particular array alone from the json response when dataID is not matched with the ParentDataID from another array in same json response using typescript feature 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 above response the value of dataId Newyork is not matched with any of the parentDataId entire array json response. So Now i want to filtered out only the second array of DataID alone to make new array.

I would like to have this validation in Typescript angular 7

My output is supposed to like below... The DataId does not have the parentDataId

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

Appreciate the help and response


Solution

  • demo in this StackBlitz Link

    my solution is like below code snippet. ts

    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');
    

    html file

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

    EDIT

    If you do not want to use second object reducedData, then below solution is fine to work.. StackBlitz Link

    component.ts

    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');
    

    component.html

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