访问json server中json data的属性,用于发送数据



我有json服务器假数据在我的react应用程序,这里是我的数据:

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

这个应用程序是一个引号显示应用程序,每个引号都有注释。在我的报价表单用户可以发送评论,但我不能访问评论属性发送数据。我如何访问这个特定的属性,并用用户的评论填充它?

Edite:

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

quotes[0].comments[0]

因为quotes是一个对象数组而comments也是一个数组所以要访问注释你必须使用数组索引或者你可以遍历注释因为它是一个数组

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]);

对于您的API端点/quotes/1/commnets,您可以使用Array.prototype.find()创建方法getQuoteCommentsById(id),并记住处理"Not found errors">

代码:

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)

相关内容

  • 没有找到相关文章

最新更新