如何使用不同的键映射多维数组?
这是一个类似的示例数组:(我的原始数组是从ajax和PHP mysql查询获得的,这就是我需要这样做的原因):
var products = [
{
id: 1,
name: 'John',
phones: {
sony:
{
brand: 'sony',
model: 'z3'
},
samsung:
{
brand: 'samsung',
model: 's7'
}
}
},
{
id: 2,
name: 'Mike',
phones: {
sony:
{
brand: 'sony',
model: 'z1'
},
nokia:
{
brand: 'nokia',
model: 'n8'
}
}
}
];
如果我尝试映射这个数组,我会得到:“未捕获的类型错误:product.phones.map不是一个函数”:
const List = ({ products, addToCart }) => {
return (
<div className="odds-3">
<div className="odds">
{products.map((product, index) =>
<div key={index}>
<p>{product.id} - {product.name}</p>
<ul>
{product.phones.map((phone, index) =>
<li key={index}>{phone.brand} - {phone.model}</li>
)}
</ul>
</div>
)}
</div>
</div>
);
}
使用这个阵列(没有手机按键),可以正常工作:
var products = [
{
id: 1,
name: 'John',
phones:
[{
brand: 'sony',
model: 'z3'
},
{
brand: 'samsung',
model: 's7'
}
]
},
{
id: 2,
name: 'Mike',
phones:
[{
brand: 'sony',
model: 'z1'
},
{
brand: 'nokia',
model: 'n8'
}
]
}
];