Home > other >  could not get expected Mapped result of array of objects in react
could not get expected Mapped result of array of objects in react

Time:09-28

I have an issue when map the array of object.

const currentYear = [{ value: 2021, label: 2021 }];

I tried with this

<div className={styles.calendar_heading}>
          Calendar for Year{" "}
          {Object.keys(currentYear).map((item, index) => (
            <span className="input-label">{item}</span>
          ))}
 </div>

output Calendar for Year 0

I expected Calendar for Year 2021 as an output. What is the issue with my code?

CodePudding user response:

You just need to use .map to get it.

const currentYear = [{
  value: 2021,
  label: 2021
}];


currentYear.map((item, index) => {
  console.log(item.value);
})

So the fixed code:

{currentYear.map((item, index) => (
   <span className="input-label">{item.value}</span>
))}

CodePudding user response:

Instead of Object.keys(currentYear).map((item, index), you should use currentYear.map((item, index) => ..., since currentYear is already an array.

{currentYear.map((item, index) => (
  <span className="input-label">{item.label}</span>
))}
  • Related