遍历嵌套在对象中的数组以查找匹配项

unf*_*low 1 javascript arrays javascript-objects

我有以下数组,其中包含一系列对象.每个对象的内部都是一个带有数组的属性.

const films = [
    {
    name: 'Ant-Man and the Wasp',
    genre: ['Action' , 'Adventure' , 'Sci-Fi' , 'Comedy']
  },
  {
    name: 'Sorry to Bother You',
    genre: ['Comedy' , 'Fantasy']
  },
  {
    name: 'Jurassic World: Fallen Kingdom',
    genre: ['Action' , 'Adventure' , 'Sci-Fi'],
  },
  {
    name: 'Incredibles 2',
    genre: ['Action' , 'Crime' , 'Drama' , 'Thriller']
  },
  {
    name: 'Deadpool 2',
    genre: ['Action' , 'Adventure' , 'Comedy']
  }
];
Run Code Online (Sandbox Code Playgroud)

我正在尝试遍历对象的数组并使用以下代码查找匹配项,但它似乎没有按预期工作.如何根据流派找到对象之间的匹配?

for (let i = 0; i < films.length; i++) {
  let film = films[i];
  let genres = film.genre;

  for (let j; j < genres.length; j++) {
    if (genres[j] == "Action") {
      console.log('Match');
    } else {
      console.log('No Match');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*yer 7

我正在假设两个不同的属性名称不是拼写错误,而且你有genredependencies.

无论哪种方式,您都可以使用单线程:

const films = [{name: 'Ant-Man and the Wasp',genre: ['Action' , 'Adventure' , 'Sci-Fi' , 'Comedy']},{name: 'Sorry to Bother You',genre: ['Comedy' , 'Fantasy']},{name: 'Jurassic World: Fallen Kingdom',dependencies: ['Action' , 'Adventure' , 'Sci-Fi'],},{name: 'Incredibles 2',dependencies: ['Action' , 'Crime' , 'Drama' , 'Thriller']},{name: 'Deadpool 2',dependencies: ['Action' , 'Adventure' , 'Comedy']}];

let actionflicks = films.filter(f => (f.genre || f.dependencies).includes( 'Action'))
console.log(actionflicks)
Run Code Online (Sandbox Code Playgroud)

至于你的代码,这不是一个糟糕的开始,但它失败了,错误.当事情不起作用时,你应养成查看控制台的习惯.它会指出你的错误.