fresh5447 fresh5447 - 4 months ago 10
Javascript Question

Trying to apply a filter to a nested array full of objects

I have a resources array which is full of objects. Each object has categories array full of objects. I am trying to apply a filter to only return resources that have category objects of a specific name. I am having some trouble with the nesting of my data object.

Here is the data I am working with:

const resources = [
{
title: 'Learn JS',
categories: [
{
name: 'javascript'
},
{
name: 'css'
}
]
},
{
title: 'Learn CSS',
categories: [
{
name: 'css'
}
]
},
{
title: 'Learn other stuff',
categories: [
{
name: 'jQuery'
},
{
name: 'javascript'
}
]
},
{
title: 'Learn node',
categories: [
{
name: 'node'
}
]
},
{
title: 'Learn React',
categories: [
{
name: 'react'
}
]
},

];


Here are my two attempts. Both return empty arrays. Am I wrong to be trying to use
maps
and
filters
. Is a
for loop
necessary?

//GOAL: Return only the resources that have a category with name 'javascript'
const attemptOne = resources.filter((item) => {
return item.categories.forEach((thing, index) => {
return thing[index] === 'javascript'
});
}).map((item) => {
return item;
})

const attemptTwo = resources.filter((item) => {
item.categories.filter((ci) => {
return ci.name === 'javascript'
}).map((nextItem) => {
return nextItem;
});
})


I have been stumbling around with this for a while, and I am not sure if I am just over complicating it our what. Thanks in advance!

Answer

You can use filter on resources. Inside the filter, since you already know that an object has categories, you should just loop through it and return true if it is the category name you are looking for.

const resources = [{
  title: 'Learn JS',
  categories: [{
    name: 'javascript'
  }, {
    name: 'css'
  }]
}, {
  title: 'Learn CSS',
  categories: [{
    name: 'css'
  }]
}, {
  title: 'Learn other stuff',
  categories: [{
    name: 'jQuery'
  }, {
    name: 'javascript'
  }]
}, {
  title: 'Learn node',
  categories: [{
    name: 'node'
  }]
}, {
  title: 'Learn React',
  categories: [{
    name: 'react'
  }]
}];

function filterViaCategory(arr, category) {
  return arr.filter((obj) => {
    for (let i = 0, length = obj.categories.length; i < length; i++) {
      if (obj.categories[i].name === category) {
        return true;
      }
    }

    return false;
  });
}

console.log(filterViaCategory(resources, 'javascript'));