I am trying to filter an array, based on some nested object. I prepared some Fiddle
Input array looks like this:
let arrayOfElements =
[
{
"name": "a",
"subElements":
[
{"surname": 1},
{"surname": 2}
]
},
{
"name": "b",
"subElements":
[
{"surname": 3},
{"surname": 1}
]
},
{
"name": "c",
"subElements":
[
{"surname": 2},
{"surname": 5}
]
}
];
I want the output for this case, to look like this:
let filteredArray =
[
{
"name": "a",
"subElements":
[
{"surname": 1}
]
},
{
"name": "b",
"subElements":
[
{"surname": 1}
]
}
];
I am using this formula to do that:
let filteredArray = arrayOfElements.filter((element) => element.subElements.some((subElement) => subElement.surname === 1));
Output is almost good, but it returns objects with all objects with surnames (better check that fiddle :D), instead of cutting them away. How can i improve the filtering ?
This way you can go as deep as you want in an array and filter elements at any level,
Spread operator
will expandelement
and then it will override thesubElements
key with filtered values.is more correctly
You can make it generic as well:
Logic
subElements
value to filtered list.Sample
Note: Arrow functions are used to keep the reference of
this
. If you are not usingthis
inside function, you can use normal functions as well.After you call
filter
, you need to pipe the results tomap
, like this:I am assuming here that you don't want to manipulate the original array. So, I am using Object.assign.