简体   繁体   English

如何在反应中访问嵌套对象

[英]how to access nested object in react

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.我尝试使用能够访问图像id等对象的地图,但是当尝试访问价格时它不起作用。 I am getting the following error我收到以下错误

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

JSON 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]

groups.user.price is an object, not an array, so map isn't a function for it. groups.user.price是一个对象,而不是一个数组,所以map不是它的函数。 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])));

Object.keys() will take an object and give you an array of all of the keys, which you can then call map on. Object.keys()将接受一个对象并为您提供所有键的数组,然后您可以调用map

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>);
    }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM