Home  >  Forum  >  Angular
Post New Query

How to filter json string in angular ?



Asked on November 07, 2018
Hello,

I want to filter the following json string using angular:
{  
   "text":"HTL",
   "value":1,
   "children":[{  
         "text":"India",
         "value":2,
         "disabled":true,
         "children":[]
      },
      {  
         "text":"Banglore",
         "value":3,
         "children":[{  
               "text":"hubli",
               "value":4,
               "children":[]
            }]
      }]
}

Here I want to filter this json string by value 3.
I want to fetch only following :
{  
         "text":"Banglore",
         "value":3,
         "children":[{  
               "text":"hubli",
               "value":4,
               "children":[]
            }]
      }

Can any one please provide solution for this?

Thanks & Regards,
Shilpa Kulkarni



Replied on November 08, 2018
You can filter recursively. Find the sample demo.


import { Component, OnInit } from '@angular/core';

const jsonData = {  
   "text":"HTL",
   "value":1,
   "children":[{  
"text":"India",
"value":2,
"disabled":true,
"children":[]
  },
  {  
"text":"Banglore",
"value":3,
"children":[{  
   "text":"hubli",
   "value":4,
   "children":[]
}]
  }]
}


@Component({
   selector: 'app-test',
   templateUrl: './test.component.html'
})
export class TestComponent implements OnInit { 
   res: [];
   ngOnInit() {
       this.filterData(jsonData.children);
        console.log(this.res);
   } 
   filterData(arrayData) {
   arrayData.filter(ob => {
   //console.log("Value:"+ ob.value);
   if (ob.value === 4 ) {
this.res = ob;
   } else if (ob.children.length !== 0) {
   //console.log("length:"+ ob.children.length);
this.filterData(ob.children);
   }
   });
   }
}


Write Answer




©2019 concretepage.com | Privacy Policy | Contact Us