skip to Main Content

i have json server fake data in my react app and here is my 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": []
}],}

this app is a quotes showing app that each quote has comments. in my quote form users can send comment but i can not access to the comments propery to send data. how can i access to this specific propery and fill it with comments that recive from users?

Edite:

i expercted get comments data with a http request, fo example http://localhost:3001/quotes/1/commnets => give me data of comments for quote 1

3

Answers


  1. quotes[0].comments[0]
    

    Since quotes is an array of object and comments is array as well so to access the comments you will have to use array indexing or you can loop through the comments since it is an array

    Login or Signup to reply.
  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]);
    Login or Signup to reply.
  3. For your API endpoint /quotes/1/commnets you can create a method getQuoteCommentsById(id) using Array.prototype.find() and remember to handle "Not found errors"

    Code:

    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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search