Skip to content
Advertisement

When traversing nested object and using match to give filtered object results in javascript it returns array of [object], [object] etc

Context I am using: Windows 11, VSCode and node v18.12.1

The code I am working on is trying to traverse several JSON objects. Then, using an array variable, the code needs to filter on certain attributes in each object, as there is more than one value that needs to filter against in each name attribute in each object.

Question The following code is working which traverses all levels of all objects and logs the person’s name, city and employer. What it needs to do is also filter out all objects that match one or more of the names in the filteredNames array, and then return all objects where they don’t contain these names.

Here is the code that’s working (as per above):

JavaScript

which gives the result:

JavaScript

Using an array variable, it needs to filter on ‘Megasystems’ and ‘Bellkrieg’ as an array in each object’s employer attribute, as there is more than one value that needs to be filtered against. It will also make it more adaptable, so it will be relatively easy to add to the filteredEmployers, as and when it’s required…

What I’ve tried I’ve searched various other solutions for the issue encountered, but they don’t seem to cater for what is needed…

This is what I currently have…

JavaScript

However, it gives the following:

JavaScript

Pagination shouldn’t be returned, and the People objects should return all attributes of the People not in the filteredEmployers list, not the People: [ [Object], [Object], [Object], [Object]

The result I’m after is as follows (or pretty similar):

JavaScript

Any advice appreciated. Thanks in advance

Advertisement

Answer

I interpret your question to mean that you want to produce an array of “People” objects, but filter out the ones whose nested “employer” property is a string which includes a substring that is one of the ones in your filter list.

If that’s correct, you can do it this way:

JavaScript

References:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement