1

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:

< LineChart title='title' data={newArr} />

Within the component, I try the following: console.log(data) and I get my array in the console. 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. However, this is a hard obstacle for me - I am new to JS (and react.js which is what I am using).

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.

3
  • As written, this const newArr: [objectOne, objectTwo] is invalid syntax. Please provide the details around where/how this is actually used. Commented Nov 23, 2021 at 18:41
  • edited @RandyCasburn Commented Nov 23, 2021 at 18:54
  • 1
    Do not do data: [{ objectOne }, { objectTwo }]. Use data: [objectOne , objectTwo ]. (remove the curly brackets). The { objectOne } creates an object with a property named objectOne whose value is the contents of the objectOne variable. Commented Nov 23, 2021 at 18:54

1 Answer 1

1

Gabriele Petrioli answered the question in the comments:

Do not do data: [{ objectOne }, { objectTwo }]. Use data: [objectOne , objectTwo ]. (remove the curly brackets). The { objectOne } creates an object with a property named objectOne whose value is the contents of the objectOne variable

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.