尝试将过滤器应用于充满对象的嵌套数组

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

我有一个充满对象的资源数组。每个对象都有充满对象的类别数组。我正在尝试仅将过滤器应用于 return 具有特定名称的类别对象的资源。我在嵌套数据对象时遇到了一些问题。

这是我正在处理的数据:

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'
      }
    ]
  },

];

这是我的两次尝试。 return 都是空数组。我尝试使用 mapsfilters 是不是错了? for loop 是必要的吗?

//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;
  });
})

我已经在这个问题上摸索了一段时间,我不确定我是否只是把它复杂化了。提前致谢!

您可以在 resources 上使用 filter。在过滤器内部,因为你已经知道一个对象有类别,你可以只使用 some 检查是否包含你要查找的类别名称

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'));

您可以尝试使用 filtersome 数组方法:

function getResourcesByCategoryName(Resources, CategoryName){

      return Resources.filter(function(resource){
               return resource
                      .categories
                      .some(function(category){ return category.name == CategoryName; });
             });
}