I have a filter criteria to apply on REST response. This response have nested sub objects. For loop going in task and filter function is not working on nested array objects. Please help me to filter the below JSON array object based on body.items[index].details.items[index].Id value.
So here I am looking to keep only the arrays in body.items.details.items which matches with 300100619883728.
JSON :
{
"error": null,
"message": {
"summary": ""
},
"status": 200,
"headers": {},
"body": {
"items": [
{
"Name": "Test1",
"LastName": "ABC",
"details": {
"items": [
{
"Id": "300100619883728",
"Status": "Draft",
"subDetails": {
"items": [
{
"CurrentAddress": "Some address"
}
],
"totalResults": 1,
"count": 1,
"hasMore": false,
"limit": 25,
"offset": 0
}
},
{
"Id": "300100619883738",
"Status": "Draft",
"subDetails": {
"items": [
{
"CurrentAddress": "Some Address"
}
],
"totalResults": 1,
"count": 1,
"hasMore": false,
"limit": 25,
"offset": 0
}
}
],
"totalResults": 2,
"count": 2,
"hasMore": false,
"limit": 25,
"offset": 0
}
},
{
"Name": "Test2",
"LastName": "ABC",
"details": {
"items": [
{
"Id": "300100619883728",
"Status": "Draft",
"subDetails": {
"items": [
{
"CurrentAddress": "Some address"
}
],
"totalResults": 1,
"count": 1,
"hasMore": false,
"limit": 25,
"offset": 0
}
},
{
"Id": "300100619883739",
"Status": "Draft",
"subDetails": {
"items": [
{
"CurrentAddress": "Some Address"
}
],
"totalResults": 1,
"count": 1,
"hasMore": false,
"limit": 25,
"offset": 0
}
}
],
"totalResults": 2,
"count": 2,
"hasMore": false,
"limit": 25,
"offset": 0
}
}
],
"totalResults": 2
},
"ok": true,
"statusText": "OK"
}
Expected result after filtering is without change in structure of array is:
{
"error": null,
"message": {
"summary": ""
},
"status": 200,
"headers": {},
"body": {
"items": [
{
"Name": "Test1",
"LastName": "ABC",
"details": {
"items": [
{
"Id": "300100619883728",
"Status": "Draft",
"subDetails": {
"items": [
{
"CurrentAddress": "Some address"
}
],
"totalResults": 1,
"count": 1,
"hasMore": false,
"limit": 25,
"offset": 0
}
}
],
"totalResults": 2,
"count": 2,
"hasMore": false,
"limit": 25,
"offset": 0
}
},
{
"Name": "Test2",
"LastName": "ABC",
"details": {
"items": [
{
"Id": "300100619883728",
"Status": "Draft",
"subDetails": {
"items": [
{
"CurrentAddress": "Some address"
}
],
"totalResults": 1,
"count": 1,
"hasMore": false,
"limit": 25,
"offset": 0
}
}
],
"totalResults": 2,
"count": 2,
"hasMore": false,
"limit": 25,
"offset": 0
}
}
],
"totalResults": 2
},
"ok": true,
"statusText": "OK"
}
filter I tried to get the desired result but could not go to nested object to access its value and filter.
const filteredObj = obj.body.items.filter(function (item) {
return item.details.items == 300100619883728;
});
res.body.items.forEach(e => { e.details.items = e.details.items.filter(i => i.Id==='300100619883728')