【问题标题】:access to a propery of json data in json server for sending data [duplicate]访问 json 服务器中的 json 数据属性以发送数据 [重复]
【发布时间】:2022-12-05 16:21:35
【问题描述】:

我的 React 应用程序中有 json 服务器假数据,这是我的数据:

{"quotes": [
{
  "id": 1,
  "quote": "Javascript is my life",
  "author": "ali pasha",
  "comments": [],
},
{
  "id": 2,
  "quote": "Learning react is very fun",
  "author": "nasim rabiei",
  "comments": []
}],}

这个应用程序是一个报价显示应用程序,每个报价都有 cmets。在我的报价表中,用户可以发送评论,但我无法访问 cmets 属性来发送数据。我怎样才能访问这个特定的属性并用从用户那里接收到的 cmets 填充它?

编辑:

我期望通过 http 请求获取 cmets 数据,例如 http://localhost:3001/quotes/1/commnets => 给我报价 1 的 cmets 数据

【问题讨论】:

  • 你试一试了吗?
  • 请与comments 分享数据,预期的 json 结果是什么?
  • 我希望通过 http 请求获取 cms 数据,例如 localhost:3001/quotes/1/commnets => 给我报价 1 的 cmets 数据

标签: javascript reactjs json database json-server


【解决方案1】:
quotes[0].comments[0]

由于引号是一个对象数组,而 cmets 也是数组,因此要访问 cmets,您将必须使用数组索引,或者您可以遍历 cmets,因为它是一个数组

【讨论】:

    【解决方案2】:

     var quotesDetail= {"quotes": [
        {
          "id": 1,
          "quote": "Javascript is my life",
          "author": "ali pasha",
          "comments": ["Sample Comments"],
        },
        {
          "id": 2,
          "quote": "Learning react is very fun",
          "author": "nasim rabiei",
          "comments": []
        }],};
        
        var inner = quotesDetail.quotes.map(function(e) {
          return e.comments;
        });
        
        console.log(inner);
        console.log(inner[0]);
        console.log(inner[1]);

    【讨论】:

      【解决方案3】:

      对于您的 API 端点 /quotes/1/commnets,您可以使用 Array.prototype.find() 创建方法 getQuoteCommentsById(id) 并记住处理“未找到错误”

      代码:

      const data = {"quotes": [{"id": 1,"quote": "Javascript is my life","author": "ali pasha","comments": [],},{"id": 2,"quote": "Learning react is very fun","author": "nasim rabiei","comments": []}]}
      
      const getQuoteCommentsById = id => {
        const quote = data.quotes.find(q => id === q.id)
        if (!quote) {
          throw `Quote with id ${id} not found!`
        }
        
        return quote.comments
      }
      
      // Comments for "quote" with id 1
      const comments = getQuoteCommentsById(1)
      
      console.log(comments)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-04
        • 2018-03-27
        • 2015-09-12
        • 2013-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-09
        相关资源
        最近更新 更多