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

时间:2018-07-06 06:13:05

标签: 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']
  }
];

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

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

4 个答案:

答案 0 :(得分:7)

我正在假设两个不同的属性名称不是拼写错误,并且您有class viewController: UIViewController { @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.tableView.separatorInset = UIEdgeInsetsMake(0, UIScreen.main.bounds.width, 0, 0) } } genre

无论哪种方式,您都可以单线完成:

dependencies

对于您的代码来说,这不是一个不好的开始,但是由于错误而失败。您应该养成在无法正常工作时查看控制台的习惯。它将指示您出了什么问题。

答案 1 :(得分:1)

此代码中有很多错别字。正确的代码应为:

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

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

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

正如Mark所指出的,数组中的某些对象具有称为“依赖项”的属性,应将其称为“流派”。同样,“ for(let j; j

答案 2 :(得分:1)

在循环流派之前应用条件

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

  if (genres != undefined){
  for (let j; j < genres.length; j++) {
    if (genres[j] == "Action") {
      console.log('Match');
    } else {
      console.log('No Match');
    }
  }
  }
}

答案 3 :(得分:1)

其他对象中的键是不同的。在最后3个对象中,键是'dependencies'而不是'genre'。因此,当遍历最后3个对象films[i].genreundefined时,将有genres.length

处出现错误

如果您还想遍历“依赖项”,请使用以下代码

for (let i = 0; i < films.length; i++) {
 let film = films[i];
 let genres = film.genre||film.dependencies;//if no 'genre' then check 'dependencies' 
 if(!genre){continue;}//if there is none then skip the loop
 for (let j; j < genres.length; j++) {
  if (genres[j] == "Action") {
   console.log('Match');
  } else {
   console.log('No Match');
  }
 }
}