使用map es6的嵌套对象数组在jsx中不起作用

时间:2018-02-12 10:44:37

标签: javascript reactjs ecmascript-6

我没有看到任何错误,只是在嵌套的对象数组上使用es6映射的空白jsx。

https://codesandbox.io/s/9jpo8z0poy

我的数据

const data = [
  {
    "name": "Main Food",
    "categories": [
      {
        "name": "Sub Food",
        "nature_of_business": [
          {
            "name": "Wholesaler"
          },
          {
            "name": "Direct sales"
          }
        ]
      }
    ]
  }
]

JSX

<div>
  natural of business: {
    (data.categories || [])
      .map(o2 => o2.nature_of_business || [])
      .map(o3 => o3.name)
      .join(', ')
  }
</div>

1 个答案:

答案 0 :(得分:3)

您正在错误地映射数据。你必须得到数组的第一项,而不是data.categories:

编辑:重新编写以便于阅读ES6。

 <div>
    natural of business: {
       data[0].categories.map(category => category.nature_of_business.map(cat => 
           <div>{cat.name}</div>
       ))
    }
 </div>

映射的摘录:

const data = [
  {
    "name": "Main Food",
    "categories": [
      {
        "name": "Sub Food",
        "nature_of_business": [
          {
            "name": "Wholesaler"
          },
          {
            "name": "Direct sales"
          }
        ]
      }
    ]
  }
];

data[0].categories.map(category => category.nature_of_business.map(cat => console.log(cat.name)));