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

fre*_*447 3 javascript arrays foreach loops javascript-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'
      }
    ]
  },

];
Run Code Online (Sandbox Code Playgroud)

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

我一直在这个问题上磕磕绊绊,我不确定我是否只是把它复杂化了。提前致谢!

dor*_*ork 6

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'));
Run Code Online (Sandbox Code Playgroud)