【发布时间】:2021-06-16 03:09:48
【问题描述】:
如果我有一个对象数组,例如:
[{"name":"chair","type":"metal"},{"name":"chair","type":"wood"},{"name":"table","type":"plastic"},...]
如何映射它以使其返回:
<h3>chair</h3>
metal
wood
<h3>table</h3>
plastic
ecc.
我尝试的是:
return (
<>
{Object.values(myarray.reduce( (c, e) => {
if (!c[e.name]) c[e.name] = e;
return c;
}, {})).map((title, index) => (
<div key={index}>
<h3>{title}</h3>
{myarray.filter(one => one.name === title)
.map((item, i) => (
<div key={i}>{item.type}</div>
))}
</div>
))}
</>
)
但它会抛出
错误:对象作为 React 子对象无效(找到:带键的对象 {名称,类型})。如果您打算渲染一组孩子,请使用 代替数组。
【问题讨论】:
-
你为什么要把所有东西都作为一个对象返回?!那么,为什么您的 return 语句包含在 { } 中。似乎在
中您应该使用 title.name 和在您的 div title.type 中。实际上您还应该将输入参数从标题重命名为对象或其他内容
-
首先在reduce 方法中返回对象条目。这就是引发错误的原因。您需要将 Html 元素或字符串返回到您的数组中
-
@marks 我省略了它上面和下面不相关的 div。我添加了空外壳
标签: javascript reactjs reduce array.prototype.map