Search code examples
javascriptarraysjsonloopsobject

Advanced Filter array of objects based on condition if its nested object has required property in it


I am trying to solve a difficult computation but i am not reaching anywhere. can someone please help

Here is a simple example.

const filterCityBy = "NY";
const data = [ 
  { name: "Harry, age: 45, city: "NY" },
  { name: "Mike, age: 36, city: "CA" }
]

const filteredData = data.filter(x = x.city === filterCityBy);

output = [ { name: "Harry, age: 45 } ]

This is self explainatory. I am trying to filter data with value filterCityBy and getting the desired output

But my requirement is as follows

const filterCityBy = "NY";
const data = [ 
  { name: "Harry, age: 45, totalCities: [{ city: "NY"}]},
  { name: "Mike, age: 36, totalCities: [{ city: "NY"}, {city: "CA"} }] }
]

output = [ { name: "Harry, age: 45 }, { name: "Mike, age: 36 } ]

How can i achieve the desired output. Harry and Mike both has city as NY in their totalCities array. I only need their name and age once the city is present in their totalCities array.

Can someone please help on how to get this.


Solution

  • Combine filter() with some() to check if some of the totalCities matches filterCityBy.

    Then use map() to get only the name and age key by removing totalCities using a destructuring assignment (...r):

    const filterCityBy = "NY";
    const data = [ 
      { name: "Harry", age: 45, totalCities: [{ city: "NY"}]},
      { name: "Mike", age: 36, totalCities: [{ city: "NY"}, {city: "CA"} ] }
    ]
    
    const output = data
        .filter(p => p?.totalCities.some(({ city }) => city === filterCityBy))
        .map(({ totalCities, ...r }) => r);
                       
    console.log(output);

    [
      {
        "name": "Harry",
        "age": 45
      },
      {
        "name": "Mike",
        "age": 36
      }
    ]