How to remove objects from arrays which have a certain attribute in react js

Advertisements

I have an array like this in ReactJS where I have some data for the regions GB (UK) and US (USA):

{
  "id": 603692,
  "results": [
    {
      "iso_3166_1": "GB",
      "release_dates": [
        {
          "certification": "",
          "descriptors": [],
          "iso_639_1": "",
          "note": "London",
          "release_date": "2023-03-24T00:00:00.000Z",
          "type": 3
        },
        {
          "certification": "15",
          "descriptors": [],
          "iso_639_1": "",
          "note": "",
          "release_date": "2023-03-24T00:00:00.000Z",
          "type": 3
        }
      ]
    },
    {
      "iso_3166_1": "US",
      "release_dates": [
        {
          "certification": "",
          "descriptors": [],
          "iso_639_1": "",
          "note": "",
          "release_date": "2023-03-20T00:00:00.000Z",
          "type": 1
        },
        {
          "certification": "R",
          "descriptors": [],
          "iso_639_1": "",
          "note": "",
          "release_date": "2023-03-24T00:00:00.000Z",
          "type": 3
        }
      ]
    }
  ]
}

I would like to delete the array blocks that have have no certification as the certification with no detail might be shown and it is not allowing the true values to be rendered, so the result should be as follows where the unrendereable objects should be deleted:

{
  "id": 603692,
  "results": [
    {
      "iso_3166_1": "GB",
      "release_dates": [
        {
          "certification": "15",
          "descriptors": [],
          "iso_639_1": "",
          "note": "",
          "release_date": "2023-03-24T00:00:00.000Z",
          "type": 3
        }
      ]
    },
    {
      "iso_3166_1": "US",
      "release_dates": [
        {
          "certification": "R",
          "descriptors": [],
          "iso_639_1": "",
          "note": "",
          "release_date": "2023-03-24T00:00:00.000Z",
          "type": 3
        }
      ]
    }
  ]
}

Is this possible. I have tried using .filter() and .find() but nothing online seemed to work. I also tried to use the newSet() function and it still did not work. I tried using this website for help removing the empty elements but to no avail. Thank you!

>Solution :

you can achieve this by using the .map() and .filter() functions in combination. The idea is to iterate over the outer array and for each object, filter its release_dates array to only include objects with non-empty certification values.

const originalData = { ... };

const filteredData = {
  id: originalData.id,
  results: originalData.results.map(region => ({
    ...region,
    release_dates: region.release_dates.filter(date => date.certification !== ""),
  })),
};

console.log(filteredData);

Leave a ReplyCancel reply