[英]Cannot access the actual value of a Javascript array of constructed objects - returns undefined
I have created an array of objects of the form我创建了一个形式的对象数组
const objectOne = {
name: 'NameOne',
data: [{x: 'dataOneX', y: 'dataOneY'},{x: 'dataTwoX', y: 'dataTwoY'}]
};
const objectTwo = {
name: 'NameOne',
data: [{x: 'dataOneX', y: 'dataOneY'},{x: 'dataTwoX', y: 'dataTwoY'}]
};
const newArr: [objectOne, objectTwo]
I then pass newArr into a component as a prop:然后我将 newArr 作为道具传递给组件:
< LineChart title='title' data={newArr} />
Within the component, I try the following: console.log(data)
and I get my array in the console.在组件中,我尝试以下操作: console.log(data)
并在控制台中获取我的数组。 However, console.log(data[0].name)
returns undefined
, and data[0]
returns the name of the original object I passed in. I am trying to access the data in this way so that I can test dynamically pulling from an API and passing the information into apexcharts.但是, console.log(data[0].name)
返回undefined
,而data[0]
返回我传入的原始 object 的名称。我正在尝试以这种方式访问数据,以便我可以测试动态拉取一个 API 并将信息传递到顶点图表。 However, this is a hard obstacle for me - I am new to JS (and react.js which is what I am using).然而,这对我来说是一个很大的障碍——我是 JS 的新手(我正在使用 react.js)。
Happy to clarify!很高兴澄清!
EDIT:编辑:
My actual code is:我的实际代码是:
const components = [
{
title: 'Headcount',
data: [{ objectOne }, { objectTwo }]
}
]
<LineChart
title="Title"
xtype="category"
data={components[0].data}
/>
And the following is what it is passed into:以下是它传入的内容:
function LineChart({ title, data }) {
console.log(data);
data.forEach((datum) => console.log(datum.name));
return(
<Box>
<Typography>{title}</Typography>
</Box>
));
}
export default LineChart;
The issue I am having is data.forEach((datum) => console.log(datum.name)) returns undefined but data is exactly as I expect it in the console.我遇到的问题是 data.forEach((datum) => console.log(datum.name)) 返回 undefined 但数据完全符合我在控制台中的预期。
Gabriele Petrioli answered the question in the comments : Gabriele Petrioli 在评论中回答了这个问题:
Do not do
data: [{ objectOne }, { objectTwo }]
.不要做data: [{ objectOne }, { objectTwo }]
。 Usedata: [objectOne, objectTwo ]
.使用data: [objectOne, objectTwo ]
。 (remove the curly brackets). (删除大括号)。 The{ objectOne }
creates an object with a property namedobjectOne
whose value is the contents of theobjectOne
variable{ objectOne }
创建一个带有名为objectOne
的属性的 object,其值是objectOne
变量的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.