我有這個資料:
const data = [
{
_id: '1',
status: 'active',
user: {
email: '[email protected]',
provider: 'google',
profile: {
image: 'https://example.com/image1.jpg',
},
},
},
{
_id: '2',
status: 'inactive',
user: {
email: '[email protected]',
provider: 'github',
profile: {
image: 'https://example.com/image2.jpg',
},
},
},
]
const head = ['_id', 'status', 'email', 'image']
const body = ['_id', 'status', 'user.email', 'user.profile.image']
我想在表格中動態顯示只顯示正文陣列中的字串。
我試過了,它可以作業_id和狀態,但不是包含點的字串
這是我嘗試過的:
data.map((item) => (
<tr key={item._id}>
{body.map((i, index) => (
<td key={index}>{item[i]}</td>
))}
</tr>
))
uj5u.com熱心網友回復:
這是我實作您的愿望輸出的方法。
使用這個功能
function getDeepObjValue (item, s) {
return s.split('.').reduce((p, c) => {
p = p[c];
return p;
}, item);
};
像這樣使用它
data.map((item) => {
return (
<tr key={item._id}>
{body.map((keys, i) => {
return <td key={i}>{getDeepObjValue(item, keys)}</td>;
})}
</tr>
);
})
如果您想查看演示,請單擊此處
uj5u.com熱心網友回復:
如果您的身體資料不是動態的,您可以這樣做:
data.map((item) => (
<tr key={item._id}>
<>
<td key={index}>{item._id}</td>
<td key={index}>{item.status}</td>
<td key={index}>{item.user.email}</td>
<td key={index}>{item.user.profile.image}</td>
<>
</tr>
))
否則你可以使用
const deeper = (data, array) => {
if(array.length > 1){
return deeper(data[array[0]], array.slice(1, array.length))
} else {
return data[array[0]]
}
}
和
data.map((item) => (
<tr key={item._id}>
{body.map((i, index) => (
<td key={index}>{deeper(item, i.split('.'))}</td>
))}
</tr>
))
類似的東西
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/497511.html
標籤:javascript 反应
