【问题标题】:Check if json contains a key in react-native检查json是否包含react-native中的键
【发布时间】:2017-07-17 09:33:10
【问题描述】:

我对 react-native(和一般的 javascript)有点陌生。按下按钮,我想在 json api 中搜索某个键(在本例中为电影)。

例如,这里是 api https://facebook.github.io/react-native/movies.json

现在按下按钮,我想检查 api 是否包含名为“黑客帝国”的电影。

网络教程指出,要获取 json,您需要以下方法:

function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson.movies;
  })
  .catch((error) => {
    console.error(error);
  });

}

这会返回一个 json 对象,但是如何查询该对象以检查它是否包含例如名为“The Matrix”的电影?

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs mobile react-native


    【解决方案1】:

    你要做的是在 json 响应中使用 Array.prototype.find() 作为 movies 数组并检查值

       function getMoviesFromApiAsync() {
    
        return fetch('https://facebook.github.io/react-native/movies.json')
          .then((response) => response.json())
          .then((responseJson) => {
            return responseJson.movies;
          })
          .catch((error) => {
            console.error(error);
          });
        }
    
        //from where you are calling getMovies
        getMoviesFromApiAsync()
             .then(response => {
                  var data = response.find((movie) => 
                       movie.title.toUpperCase().indexOf('THE MATRIX') > -1
                  )
                  console.log(data)
                  if(data) {
                      console.log('found');
                  }
             })
    

    其他选项是使用

    Array.prototype.some()

     var data = response.some((movie) => movie.title.toUpperCase().indexOf('THE MATRIX') > -1)
    

    Array.prototype.filter()

     var data = response.filter((movie) => movie.title.toUpperCase().indexOf('THE MATRIX') > -1)
    

    【讨论】:

    • 你不应该检查 indexOf > -1 吗?
    • @RRikesh,感谢您指出这一点,刚刚更新了答案
    • @ShubhamKhatri 酷,非常感谢,它可以工作:)。不过还有一个问题。当我单击按钮而不是登录到控制台时,如何让它显示显示 json 对象名称的警报?在该方法中,警报似乎不起作用。
    • 你需要 React Native Alert API facebook.github.io/react-native/docs/alert.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多