Reputation: 751
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
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:
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
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