theCoder
theCoder

Reputation: 751

how to Filter on nested data in an Array using ionic3

I am trying to filter an Array based on the user name and show It but when I try to filter it doesn't show any data. User Structure Is like this

     buyer: [{
              address: ""
              contactNo: ""
              email: "[email protected]"
              name: "user"}]
    cutomerContact: "3058989778"
    orderDate: "2019-07-31T12:10:11.818Z"
    orderType: "general"

and my code to filter array is

this.userOrders = this.filteredOrders.filter(x => x.buyer = x.buyer.name == this.userName)

I have no Idea how to filter a nested data any Help would be appreciated

Upvotes: 0

Views: 135

Answers (2)

Sunil Kashyap
Sunil Kashyap

Reputation: 2984

User filter to filter the main array and some function to check the condition.

The some() method executes the function once for each element present in the array:

  • If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining values)
  • Otherwise it returns false

  name = 'user';
  
  filterData = [
                  {
                    "buyer": [
                      {
                        "address": "",
                        "contactNo": "",
                        "email": "[email protected]",
                        "name": "user"
                      }
                    ],
                    "cutomerContact": "3058989778",
                    "orderDate": "2019-07-31T12:10:11.818Z",
                    "orderType": "general"
                  },
                  {
                    "buyer": [
                      {
                        "address": "",
                        "contactNo": "",
                        "email": "[email protected]",
                        "name": "test"
                      }
                    ],
                    "cutomerContact": "3058989778",
                    "orderDate": "2019-07-31T12:10:11.818Z",
                    "orderType": "general"
                  }
                ]
                
                
  let result = this.filterData.filter( (x) => {
    return x.buyer.some(y => y.name == name)
  })
  
  console.log(result)

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222582

Try the following

DEMO

let testArray =  [
  {
    "name": "SO",
    "buyer": [
      {
        "address": "",
        "contactNo": "",
        "email": "[email protected]",
        "name": "user"
      }
    ],
    "cutomerContact": "3058989778",
    "orderDate": "2019-07-31T12:10:11.818Z",
    "orderType": "general"
  }
];


let filteredArray = testArray.filter((element) => element.buyer.some((subElement) => subElement.name == 'user')); 
  
console.log(filteredArray);

Upvotes: 0

Related Questions