在React中基于特定属性将对象数组中的数据渲染为标题



我有一个像下面这样的对象数组-

{
name:"Thor",
universe:"Marvel",
type:"God"
},
{
name:"Batman",
universe:"DC",
type:"Human"
},
{
name:"Iron man",
universe:"Marvel",
type:"Human"
},
];

现在,让我们假设我想要渲染对象,使类型Human的细节类型God的详细信息在一起。

基本上,我想显示基于类型的数据属性如下-
**Human**
name: Batman   universe:DC
name: Iron man universe:Marvel
**God**
name: Thor universe: Marvel

我可以帮你分类。你可以渲染你自己。

const data=[{
name:"Thor",
universe:"Marvel",
type:"God"
},
{
name:"Batman",
universe:"DC",
type:"Human"
},
{
name:"Iron man",
universe:"Marvel",
type:"Human"
},
];
const category={};
for(let i of data){
category[i.type]??=[]
category[i.type].push(i)
}

类别:

{
"God":[
{
"name":"Thor",
"universe":"Marvel",
"type":"God"
}
],
"Human":[
{
"name":"Batman",
"universe":"DC",
"type":"Human"
},
{
"name":"Iron man",
"universe":"Marvel",
"type":"Human"
}
]
}

首先将数据类型格式化为易于使用的数据类型:请看下面的例子:

function App() {
const characters = [
{
name: "Thor",
universe: "Marvel",
type: "God",
},
{
name: "Batman",
universe: "DC",
type: "Human",
},
{
name: "Iron man",
universe: "Marvel",
type: "Human",
},
];
const charactersObj = {};
characters.forEach((character) => {
const { type } = character;
if (charactersObj[type]) {
const currentArray = [...charactersObj[type]];
currentArray.push(character);
charactersObj[type] = currentArray;
} else {
charactersObj[type] = [character];
}
});
return (
<div>
{Object.entries(charactersObj).map(([charType, charData]) => {
return (
<div>
<p> {charType}</p>
{charData.map(({name, universe}) =>  <p>name: {name} universe: {universe} </p>)}

</div>
);
})}
</div>
);
}

无需更改数据结构,只需映射类型

const App = () => {
return (
<div>
Human:
<div>
{heroes.map((hero) =>
hero.type === "Human" ? <div>{hero.name}</div> : null,
)}
</div>
God:
<div>
{heroes.map((hero) =>
hero.type === "God" ? <div>{hero.name}</div> : null,
)}
</div>
</div>
);
};

你可以尝试这样做

const data = [{
name:"Thor",
universe:"Marvel",
type:"God"
},
{
name:"Batman",
universe:"DC",
type:"Human"
},
{
name:"Iron man",
universe:"Marvel",
type:"Human"
},
];
const transform = data => data.reduce((res, {type, ...rest}) => {
return {
...res,
[type]: [...(res[type] || []), rest]
}
},{})
const toTemplate = (type, data) => {
return `**${type}**
${data.map(({name, universe}) => `name: ${name}   universe: ${universe}`).join('n')}`
}
const toHtml = (data) => Object.entries(transform(data)).map(d => toTemplate(...d)).join('nn')
console.log(toHtml(data))

这是一个简单的解决方案,它将工作。

const data = [{
name: "Thor",
universe: "Marvel",
type: "God"
},
{
name: "Batman",
universe: "DC",
type: "Human"
},
{
name: "Iron man",
universe: "Marvel",
type: "Human"
},
];
let obj = {
Human: 1,
God: 2
}
console.log(data.sort((a, b) => obj[a.type] - obj[b.type]))

最新更新