React:使用不同的键映射多维数组 [英] React: Map multidimensional array with different keys
本文介绍了React:使用不同的键映射多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用不同的键映射多维数组?
这是一个类似的示例数组:(我的原始数组是从ajax和PHP mysql查询获得的,这就是我需要这样做的原因):
How could I map a multidimensional array with differents keys? This is a example array similar: (my original array is obtained from ajax and PHP mysql query that's why I need to do this):
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'
}
}
}
];
如果我尝试映射此数组,我得到:'未捕获的TypeError:product.phones.map不是函数':
If I try to map this array I get: '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>
);
}
使用此阵列(没有手机密钥),工作正常:
With this array (without phones keys), works fine:
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'
}
]
}
];
推荐答案
产品
不是数组,因此 map
函数不起作用。尝试
products
isn't an array so the map
function won't work. Try
{Object.keys(product.phones).map((phone, index) =>
<li key={index}>{product.phones[phone].brand} - {product.phones[phone].model}</li>
)}
而不是。
这篇关于React:使用不同的键映射多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文