如何从标题包含给定单词的json文件中分离所有标题?

问题描述 投票:0回答:3

这里有一段函数只是将React中的元素命名为box的道具。在这个MovieDatabase是一个JSON文件,其中包含不同电影的标题。我只想看那些名字包含“星球大战”的电影。

const showMovies = MovieDatabase.map((movie) =>{
const aa = movie.title.contains("Star Wars")
return (
    <Box movieName = {aa} />
);})
javascript json reactjs
3个回答
2
投票

我认为最好从组件中分离出来。

这是一种方式:

// assuming the DB is something like this based on your .map example
const MovieDatabase = [
    { title: 'Star Wars: II', id: 0 },
    { title: 'Star Wars: I', id: 1 },
    { title: 'Star Wars: IV', id: 2 },
    { title: 'Moon', id: 3 }
  ]

// array of star wars movies
const starWars = MovieDatabase.filter(movie => movie.title.includes('Star Wars'))

// component to render movies ( doesn't care about anything but rendering )
const MovieBoxes = movies => movies.map(movie => (
  <Box key={movie.id} movieName={movie.title} />
)

您可以通过将过滤器包装在一个带有关键字的函数中并将其传递给包含以便您可以找到任何电影来进一步改进它。


1
投票

你可以使用array.filter()

const array = [{
  title: 'Star Wars',
  duration: 107
}, {
  title: 'Star Wars',
  duration: 103
}, {
  title: 'Lord Of The Rings',
  duration: 500
}]

const filterArray = array.filter(film => film.title === 'Star Wars')

console.log(filterArray)

0
投票

你也可以在你的null中返回map()作为你的过滤器,而不需要明确地使用Array#filter(),因为React不会渲染

const showMovies = MovieDatabase.map((movie) =>{
    const {title} = movie
    return title.contains("Star Wars") ? <Box movieName = {title} /> : null;
})
© www.soinside.com 2019 - 2024. All rights reserved.