Sanjay Tiwari
Sanjay Tiwari

Reputation: 133

How to integrate array.map in React Js

Here is my Jason data and code that i am using map() for populating my data but getting some error, below is my code

var data = [
  {
    categorytitle: "Shoes",
    category: [
      {
        Category1: "Boots"
      },
      {
        Category2: "Sneakers"
      },
      {
        Category3: "Flats"
      },
      {
        Category4: "Booties"
      },
      {
        Category5: "Mules"
      },
      {
        Category6: "Heels/Pumps"
      },
      {
        Category7: "Clogs"
      },
      {
        Category8: "Slippers"
      },
      {
        Category9: "Sandals"
      },
      {
        Category10: "Sale"
      },
      {
        Category11: "Shop All"
      }
    ]
  }
];

also please find the populating code at below...

{data.map((el, e) => (
                    <div {...el} key={e}>
                      <h3>{el.categorytitle}</h3>
                      <ul>
                        <li>{el.category[e]}</li>
                      </ul>
                    </div>
                  ))}

Please guide me how i can display Category1 .... in list?

Upvotes: 2

Views: 371

Answers (3)

Aziz.G
Aziz.G

Reputation: 3721

const data = [{
  categorytitle: "Shoes",
  category: [{
      Category1: "Boots"
    },
    {
      Category2: "Sneakers"
    },
    {
      Category3: "Flats"
    },
    {
      Category4: "Booties"
    },
    {
      Category5: "Mules"
    },
    {
      Category6: "Heels/Pumps"
    },
    {
      Category7: "Clogs"
    },
    {
      Category8: "Slippers"
    },
    {
      Category9: "Sandals"
    },
    {
      Category10: "Sale"
    },
    {
      Category11: "Shop All"
    }
  ]
}];

const category = data.forEach(({
  category
}) => {
  Object.values(category).map((value, index) => {
    console.log(value[`Category${index +1 }`]);
  })
});

For React JSX it should be something like :

{data.forEach(({ category }) => {
      Object.values(category).map((value, index) => {
        <span> {value[`Category${index + 1}`]} </span>;
      });
    })}

Upvotes: 0

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

You can do something like below

   {data.map((ele, index) => (
                <div key={"Key-"+index}>
                  <h3>{ele.categorytitle}</h3>
                  <ul>
                    {Array.isArray(ele.category) && ele.category.map((d, i) => (<li key={"Key-"+i}>{d[`Category${i+1}`]}
                    </li>))}
                  </ul>
                </div>
              ))}

Upvotes: 1

Shivam
Shivam

Reputation: 3131

Try something like this: You need to loop through the category array

data[0].category.map((el, i) => {
    console.log(el['Category' + i++])
    console.log(i)
    return el['Category' + i++];
})

Upvotes: 0

Related Questions