javascript - 如何使用点符号访问此对象数组中的嵌套值?
问题描述
import React, { Component } from 'react';
import axios from 'axios';
class Home extends Component {
state = {
responses: []
}
componentDidMount() {
this.fetchQuestionAnswers();
}
fetchQuestionAnswers = () => {
if (this.state.activeSupervisionId) {
axios.get('/question/response/' + this.state.activeSupervisionId).then(res => {
this.setState({ responses: res.data.data || [] });
console.log(this.state.responses[0].value)
// dot notation work here inside the function
}).catch(err => console.error(err));
}
}
render() {
console.log(this.state.responses[0].value)
// dot notation not working here under render function but the result of // console.log(this.state.responses[0]) is printed
return (
)
}
}
export default Home;
我从作为对象数组发送的 API 中获取数据。所以可以说我设置了responses: res.data.data
. 响应控制台的结果如下所述。
var responses = [0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…},...]
指数值
我将使用 0 索引对象作为我想要实现的示例。我已经搜索了其他答案,但无法弄清楚。
0: {
id: 5,
questionId: 1,
score: "0",
text: "Are there any others",
value: {
designations: {
CCO: { no: "3" },
CDD: { no: "1" },
DSNO: { no: "1" }
},
reaportedStaff: [ "DSNO", "CCO", "CDD" ]
staffLivingInQuarter: "yes"
totalReaportedStaff: 5
}
}
我想知道如何使用点表示法或其他方法(即 id、score、text、CCO 否)访问数组中对象内的属性值?
请注意,我已经尝试过responses[0].value
并打印了TypeError: Cannot read properties of undefined (reading 'value')
解决方案
推荐阅读
- npm - 尝试创建 React App 时出现 Enoent 错误
- javascript - ExpressJS 和 PDFKit - 在内存中生成 PDF 并发送到客户端以供下载
- r - 最小化模糊匹配和 for 循环中的计算次数
- python - __getattr__ 什么时候被触发?
- php - 在 Laravel 中合并集合的值
- java - 为什么通过在 JPA 中加入两个不相关的实体来使用投影获取数据时没有设置投影字段?
- javascript - 使用 Knockout 从数组中设置正确文本时遇到问题
- django - 测试套接字激活失败,Django 和 Gunicorn
- ansible - 没有“FAILED”json输出的ansible中的条件
- html - 两列弹性布局,内容向中间对齐