繁体   English   中英

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

[英]Trying to apply a filter to a nested array full of objects

我有一个充满对象的资源数组。 每个对象都有充满对象的类别数组。 我试图将过滤器仅返回具有特定名称的类别对象的资源。 我在嵌套数据对象时遇到了一些麻烦。

这是我正在使用的数据:

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

];

这是我的两次尝试。 两者都返回空数组。 我试图使用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;
  });
})

我已经绊了好一阵子了,我不确定我是否只是将其复杂化了。 提前致谢!

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

function getResourcesByCategoryName(Resources, CategoryName){

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

您可以对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')); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM