Filtering Item from Nested Object Array in Typescript

Filter based on value of nested array of objects in Typescript

Because with map, you need to return the new item. (I also fixed your object structure to make it valid):

const compareResults = [{    "domain": "d1",    "technology": "Java",    "artifacts": [{      "artifactName": "app1",      "hasVersionDiff": true,      "environment": ["DEV", "SQA"],      "version": ["Not Available", "1.0-R1"]    }]  },
{ "domain": "d2", "technology": ".net", "artifacts": [{ "artifactName": "app4", "hasVersionDiff": false, "environment": ["DEV", "SQA"], "version": ["1.0-R1", "1.0-R1"] }] }];
const modified = compareResults.map(function(ComparisonResult) { ComparisonResult.artifacts = ComparisonResult.artifacts.filter(x => x.hasVersionDiff); return ComparisonResult;});
console.log(modified);
.as-console-wrapper { max-height: 100% !important; top: auto; }

filter array of nested objects in TypeScript

Your question is a little misleading. You want to reduce both the menus and submenus so you need to do a reduce, not a filter.

Not inserting the menus that are empty and filtering the submenus by the direction.

const directions = [4];
this.mesMenus = res.reduce((arr, cur) => {
const submenus = cur.Liste_Sous_Menus
.filter(dir => dir.Liste_Direction_Menu
.some(m => directions
.some(d => m.NUA_ID_Direction == d)));
if(submenus.length > 0) {
cur.Liste_Sous_Menus = submenus;
arr.push(cur);
}
return arr;
},[]);

Filtering item from nested object array in typescript

Use recursive calls like this:

    private filterItems(items:Array){
return this.items.filter(obj => obj.label !== undefined)
.forEach(item=> if(item.items) {item.items=this.filterArray(item.items)};
}

with the first call of items=this.filterItems(items)

Probably this needs some fixing as I wrote it here without compilators help, but it should give you a very solid start.

Filtering array of nested arrays object in Typescript

this.payments = list.map((i)=>{
return {
budget: i.budget,
amtPercentage: i.percentage ? i.percentage : 0,
rulename: i.rulename,
group: this.group.filter((x) => i.budget === x.budget)
}
})

EDIT simplification:

this.payments = list.map((listElement) => ({
...listElement,
amtPercentage: listElement.percentage || 0,
group: this.group.filter((groupElement) => listElement.budget === groupElement.budget)
}))

Filtering array of objects by searching nested object property

You can filter the childrenArray by checking with Array.some() if it contains at least one color (or every for all of them) and Array.includes():

const childrenArray = [  {name:'somevalue',favColors:['red','purple','green']},  {name:'somevalue1',favColors:['blue','brown','pink']},  {name:'somevalue2',favColors:['orange','yellow']}]
const getElementsByColors = ({ colors }) => childrenArray.filter(({ favColors }) => colors.some(color => favColors.includes(color)) // or every for all of them )
const result = getElementsByColors({colorBook:'somevalue4', colors:['red','blue']})
console.log(result)

Filtering array of objects by searching nested object properties

You could use Array#filter with looking into the nested arrays by using Array#some.

If the tag is found in a nested array, then iteration stops and the result is given back to the filter callback.

var array = [{ category: 'Business', users: [{ name: 'Sally', tags: [{ tag: 'accounting' }, { tag: 'marketing' }] }, { name: 'Bob', tags: [{ tag: 'sales' }, { tag: 'accounting' }] }] }, { category: 'Heritage', users: [{ name: 'Linda', tags: [{ tag: 'Italy' }, { tag: 'Macedonia' }] }, { name: 'George', tags: [{ tag: 'South Africa' }, { tag: 'Chile' }] }] }],    tag = 'marketing',    result = array.filter(a => a.users.some(u => u.tags.some(t => t.tag.includes(tag))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter nested arrays by searching

The following function should do the trick for you:

function searchData(dataArray, searchTerm) {
return dataArray.flatMap(obj => {
const objHasSearchTerm = Object.entries(obj)
.some(([key, value]) => key !== 'children' && String(value).toLowerCase().includes(searchTerm.toLowerCase()));

if (objHasSearchTerm && !obj.children) return [obj]

const matchedChildren = searchData(obj.children ?? [], searchTerm);
return objHasSearchTerm || matchedChildren.length > 0
? [{
...obj,
children: matchedChildren,
}]
: [];
})
}

It recursively goes through the data array, looks for any entries that have the specified search term, and if so, places it into the newly constructed object.

let allData = [
{
category: 15,
label: "Components",
value: "a614741f-7d4b-4b33-91b7-89a0ef96a099",
children: [
{
category: 1,
label: "Carousel1",
diId: 55946,
// as you can see there are many children nested array of object
children: [{ label: "nodatafoundmessage", value: "47d18fb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "be5e027b-9163-4cfb-8816-0c8e3b816086"
},
{
category: 2,
label: "Checkbox1",
diId: 193909,
children: [{ label: "datafound", value: "47d18sb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "045e8786-2165-4e1e-a839-99b1b0ceef57"
}
]
},
{
value: "4be22726-850c-4905-ab3b-039fcf607d55",
label: "Default",
children: [
{
category: 5,
defaultValueType: 1,
label: "Empty",
toType: "String",
value: "ebedb43f-4c53-491f-8954-d030321845cd"
},
{
category: 5,
defaultValueType: 2,
label: "Space",
toType: "String",
value: "2d0e1429-572b-4f21-9f83-3340bafff95a"
},
{
category: 5,
defaultValueType: 8,
label: "Current Username",
toType: "String",
value: "25f6b40a-33c7-4f17-b29d-99e8d1e4e33c"
},
{
category: 5,
defaultValueType: 9,
label: "Current Location",
toType: "Location",
value: "ed59da2f-318d-4599-9085-4d9d769a27d7"
}
]
},
{
category: 4,
label: "Fixed Value",
isFixed: true,
value: "28e90e3e-a20b-4499-9593-061a7d1e7bd6"
// as you can see there is no children in this object
}
];



function searchData(dataArray, searchTerm) {
return dataArray.flatMap(obj => {
const objHasSearchTerm = Object.entries(obj)
.some(([key, value]) => key !== 'children' && String(value).toLowerCase().includes(searchTerm.toLowerCase()));

if (objHasSearchTerm && !obj.children) return [obj]

const matchedChildren = searchData(obj.children ?? [], searchTerm);
return objHasSearchTerm || matchedChildren.length > 0
? [{
...obj,
children: matchedChildren,
}]
: [];
})
}

console.log('----- Search: nodata')
console.log(JSON.stringify(searchData(allData, 'nodata'), null, 2))
console.log('----- Search: spa')
console.log(JSON.stringify(searchData(allData, 'spa'), null, 2))

How to access nested array of objects element using filter in Angular?

const input = {"centers":[{"center_id":603425,"name":"Childrens Hospital","fee_type":"Paid","sessions":[{"session_id":"4e687873-5ecc-4086-893e-31a1b450ca3b","date":"22-05-2021","available_capacity":0,"min_age_limit":18,},{"session_id":"54347880-3090-4962-aa56-451fbaca16e1","date":"22-05-2021","available_capacity":25,"min_age_limit":45,}]},{"center_id":195100,"name":"playschool thousandlights","fee_type":"Free","sessions":[{"session_id":"d4446397-f35e-4140-9778-6af9d8b92a5c","date":"22-05-2021","available_capacity":15,"min_age_limit":45,},{"session_id":"7553c7e5-d7ec-456c-af88-0a02756cbdbb","date":"23-05-2021","available_capacity":19,"min_age_limit":18,}]},{"center_id":254600,"name":"calcicut Hospital","fee_type":"Free","sessions":[{"session_id":"d4446397-f35e-4140-9778-6af9d8b92a5c","date":"22-05-2021","available_capacity":15,"min_age_limit":18,},{"session_id":"7553c7e5-d7ec-456c-af88-0a02756cbdbb","date":"23-05-2021","available_capacity":19,"min_age_limit":18,}]},{"center_id":264987,"name":"sholings GH","fee_type":"Free","sessions":[{"session_id":"d4446397-f35e-4140-9778-6af9d8b92a5c","date":"22-05-2021","available_capacity":15,"min_age_limit":45,},{"session_id":"7553c7e5-d7ec-456c-af88-0a02756cbdbb","date":"23-05-2021","available_capacity":19,"min_age_limit":45,},{"session_id":"7553c7e5-d7ec-456c-af88-0a02756cbdbb","date":"24-05-2021","available_capacity":25,"min_age_limit":18,}]},{"center_id":254566,"name":"greenland Hospital","fee_type":"Free","sessions":[{"session_id":"d4446397-f35e-4140-9778-6af9d8b92a5c","date":"22-05-2021","available_capacity":15,"min_age_limit":45,},{"session_id":"7553c7e5-d7ec-456c-af88-0a02756cbdbb","date":"23-05-2021","available_capacity":19,"min_age_limit":45,}]}]}
const res = input.centers
.map(({sessions, ...r}) => ({
...r,
sessions: sessions.filter(e => e.min_age_limit === 18)
}))
.filter(e => e.sessions.length)
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

filter nested array of objects at multiple level and get back the matched objects in the array

You could take a function which takes an array or later items and returns an array with either the objects which contains wanted value, or nothing.

const
getFilteredData = (array, value) => array.reduce((r, o) => {
let { items = [], ...rest } = o,
values = Object.values(rest);
if (values.some(v => v.toString().includes(value))) {
r.push(o);
} else {
items = getFilteredData(items, value);
if (items.length) r.push({ ...o, items });
}
return r;
}, []),
data = [{ id: "m1", name: "data1", val: "D", items: [{ id: "d1", name: "datanested1", val: "D", items: [{ id: "1", name: "direct Data", val: "E" }, { id: "2", name: "test", val: "E" }] }] }, { id: "d2", name: "data2", val: "D", items: [{ id: "21", name: "test21", val: "E" }, { id: "22", name: "test23", val: "E" }] }, { id: "d3", name: "data23", val: "D", items: [{ id: "31", name: "test data 3", val: "E" }, { id: "32", name: "test data 4", val: "E" }] }],
testdata = [{ id: "d3", name: "data23", val: "D", items: [ { id: "31", name: "b", val: "E" }, { id: "32", name: "c", val: "E" } ] }];

console.log("data", getFilteredData(data, "data"));
console.log("datanested1", getFilteredData(data, "datanested1"));
console.log("direct", getFilteredData(data, "direct"));
console.log("test", getFilteredData(data, "test"));
console.log("2", getFilteredData(data, "2"));
console.log("testdata", getFilteredData(testdata, "b"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Filtering array of objects with arrays based on nested value

This way you can go as deep as you want in an array and filter elements at any level,

arrayOfElements.map((element) => {
return {...element, subElements: element.subElements.filter((subElement) => subElement.surname === 1)}
})

Spread operator will expand element and then filtered subElements will override the subElements in element.



Related Topics



Leave a reply



Submit