【问题标题】:Trying to apply a filter to a nested array full of objects尝试将过滤器应用于充满对象的嵌套数组
【发布时间】:2016-11-25 19:43:30
【问题描述】:

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

这是我正在处理的数据:

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

我一直在纠结这个问题,我不确定我是不是把它复杂化了。提前致谢!

【问题讨论】:

  • forEach 返回一个值不会完成任何事情。也许您正在寻找Array#some

标签: javascript arrays loops foreach javascript-objects


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      相关资源
      最近更新 更多