-1

Consider the following JSON:

const JSON = [
  {
    "Name":"Ben Davies",
    "JobsList":[
       {
        "Company":"Company1",
        "Date":"01/01/01",
       },
       {
        "Company":"Company2",
        "Date":"01/01/01",
       },
       {
        "Company":"Company3",
        "Date":"01/01/01",
       }
    ]
 }
]

I want to pass the "Jobs" into a new component on the page, like so:

const [jobs] = useState(JSON);

return(
  <CareerList  
    jobs={jobs} 
  />
);

Now on the CareerList component, if I check the length of the jobs prop, I only get 1, I understand that this is because I'm not looping through the array, so how do I loop through the array? How do I make the length the desired 3 in this case.

const CareerList = (props) => {

  const allJobs = props.jobs;
  console.log(allJobs.length)
}

Thanks in advance.

Ben Davies
  • 426
  • 3
  • 14
  • Well the length of the `jobs` prop *is* 1, there's only one person there. If you want the length of `JobsList` then you have to loop through `jobs` and then loop through `JobsList` of each person. (Also, you don't have JSON, you have an array of objects.) – Guy Incognito Feb 14 '23 at 13:10
  • See [How can I access and process nested objects, arrays, or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Guy Incognito Feb 14 '23 at 13:12

1 Answers1

0

If you only want the JobsList then just pass that to the useState as follows:

const JSON = [
  {
    "Name":"Ben Davies",
    "JobsList":[
       {
        "Company":"Company1",
        "Date":"01/01/01",
       },
       {
        "Company":"Company2",
        "Date":"01/01/01",
       },
       {
        "Company":"Company3",
        "Date":"01/01/01",
       }
    ]
 }
]
const JobsList = JSON[0].JobsList
const [jobs, setJobs] = useState(JobsList);

Although I would recommend that you do not rename JobsList to jobs. Just keep it the same name.

Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63