如何映射具有不同键的多维数组?这是一个类似的示例数组:(我的原始数组是从 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'
}
}
}
];
如果我尝试映射这个数组,我会得到:'Uncaught TypeError: product.phones.map is not a function':
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'
}
]
}
];