Filtering data through nested array of objects

Hi,

This is what my JSON looks like https://jsonblob.com/b54eb83c-3dd7-11eb-ac66-93d12dbf87d3

It has an array objects. in each object, I want to filter my data by ChartData.dataset.seriesname

This is what my output should look like.
https://jsonblob.com/42d6309c-3fd1-11eb-99aa-c7c83bc7b601

This is what I did. But it is not filtering.

function transform(data) {
   return data
     .filter(function(obj) {
       return obj.ChartData.dataset.filter(function(item){
         return item.seriesname === "United States"
       })
     })
 }

Thanks!

Hey @iamadoer,

It looks like your function is doing unnecessary filtering that will not filter it right. If you want to filter through the seriesname, than just straight up filter from it ,like this:

data.filter((obj) => {
  return obj.CharData.dataset.seriesname === "United States"
});

Thanks for replying @Catalactics. Your answer would be correct if dataset is an object.
But, in my JSON, dataset is an array of objects and not an object.

Sorry, I didn’t see it. Anyways, do you want to filter the whole object? or do you just want to get the dataset?

Whole object. This is how the output should look like for seriesname===“United States”
https://jsonblob.com/42d6309c-3fd1-11eb-99aa-c7c83bc7b601

1 Like

Unfortunately, there is really not an easy way to solve this(I think, there may be that I don’t know of). This is because most of JavaScript’s array methods are not mutating but creating a new array so you have to mutate it yourself after the filter is done. Anyways, you would need to filter the array by filtering the dataset and check if it has a value. Then you have to manually filter and mutate the newly made array. It would look like:

function transform(data) {
  let ret = data.filter(obj => {
    return obj.ChartData.dataset.filter(item => {
      return item.seriesname == "United States"
    }).length >= 1;
  })
  
  ret.forEach(data => {
    data.ChartData.dataset = data.ChartData.dataset.filter(item => {
      return item.seriesname == "United States"
    });
  });
    
  return ret;
}

Hope this helps :slight_smile:

1 Like

Thanks a lot. This works!

1 Like