LaVOZs

The World’s Largest Online Community for Developers

'; javascript - how to access nested object in react - LavOzs.Com

I am unable to access price in react component. I tried using the map able to access the object like images and id but when trying to access the value in price it not working. I am getting the following error

Map is not a function for {groups.map((user, index) => (user.price.map(i=><p>i.regular</p>)

JSON

[
  {
    "id": "shop/new/all-new",
    "name": "All New",
    "categoryType": "subcat",
    "groups": [
      {
        "id": "modern-leaning-narrow-bathroom-shelf-h5074",
        "name": "Modern Leaning Narrow Bathroom Shelf",
        "links": {
          "www": "https://www.westelm.com/products/modern-leaning-narrow-bathroom-shelf-h5074/"
        },
        "price": { "regular": 149, "selling": 111.75, "type": "special" },
        "thumbnail": {
          "size": "m",
          "meta": "",
          "alt": "",
          "rel": "thumbnail",
          "width": 363,
          "href": "https://www.westelm.com/weimgs/ab/images/wcm/products/201952/0001/modern-leaning-narrow-bathroom-shelf-m.jpg",
          "height": 363
        },
        "hero": {

        },
        "images": [
          {  },
          {

          },
          {
                      }
        ],
        "swatches": [],
        "messages": [],
        "flags": [
       ],
        "reviews": {
         }
      },
      [..more objects]

you cant use map on an object.

Try this

   {groups.map((user, index) => {
      return (<div>
       {Object.keys(user.price).map(i=><p>user.price[i]</p>}
      </div>);
    }}

groups.user.price is an object, not an array, so map isn't a function for it. Instead you may want to do something like

const thing = {
  "id": "shop/new/all-new",
  "name": "All New",
  "categoryType": "subcat",
  "groups": [{
    "id": "modern-leaning-narrow-bathroom-shelf-h5074",
    "name": "Modern Leaning Narrow Bathroom Shelf",
    "links": {
      "www": "https://www.westelm.com/products/modern-leaning-narrow-bathroom-shelf-h5074/"
    },
    "price": {
      "regular": 149,
      "selling": 111.75,
      "type": "special"
    },
}]};

thing.groups.map(group => Object.keys(group.price).map(priceOpt => console.log(priceOpt, group.price[priceOpt])));