尝试将过滤器应用于充满对象的嵌套数组 [英] Trying to apply a filter to a nested array full of objects

查看:95
本文介绍了尝试将过滤器应用于充满对象的嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

];

这是我的两次尝试.两者都返回空数组.我尝试使用mapsfilters是错误的. for loop是否必要?

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!

推荐答案

您可以在resources上使用filter.在过滤器内部,由于您已经知道对象具有类别,因此可以使用

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

这篇关于尝试将过滤器应用于充满对象的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆