Trying to apply a filter to a nested array full of

2020-02-15 02:50发布

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!

2条回答
神经病院院长
2楼-- · 2020-02-15 03:12

You can use filter on resources. Inside the filter, since you already know that an object has categories, you can just use some to check if the category name you are looking for is included

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 => obj.categories.some(cat => cat.name === category));
}

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

查看更多
我想做一个坏孩纸
3楼-- · 2020-02-15 03:19

You can try using filter and some array methods:

function getResourcesByCategoryName(Resources, CategoryName){

      return Resources.filter(function(resource){
               return resource
                      .categories
                      .some(function(category){ return category.name == CategoryName; });
             });
}
查看更多
登录 后发表回答