2 回答
TA贡献1850条经验 获得超11个赞
这是示例代码
const person = {
con: [
{ category: "A", name: "john" },
{ category: "A", name: "john" },
{ category: "B", name: "rahul" },
{ category: "B", name: "jay" },
{ category: "C", name: "dave" },
{ category: "D", name: "alex" },
{ category: "D", name: "alex" },
{ category: "E", name: "sam1" },
{ category: "F", name: "sam2" },
{ category: "G", name: "sam3" },
]
};
const duplicateCheck = [];
person.con && person.con.map((data, index) => {
if (duplicateCheck.includes(data.category))
return null;
duplicateCheck.push(data.category);
return data;
}).filter((e)=>(e))
// Above code returns filtered out array
输出:
[ { category: 'A', name: 'john' },
{ category: 'B', name: 'rahul' },
{ category: 'C', name: 'dave' },
{ category: 'D', name: 'alex' },
{ category: 'E', name: 'sam1' },
{ category: 'F', name: 'sam2' },
{ category: 'G', name: 'sam3' } ]
TA贡献1804条经验 获得超3个赞
我认为它应该看起来像这样:稍微重组您的数据以使其更容易渲染然后渲染它。
const person = {
con: [
{ category: "A", name: "john" },
{ category: "A", name: "doe" },
{ category: "B", name: "rahul" },
{ category: "B", name: "jay" },
{ category: "C", name: "dave" },
{ category: "D", name: "alex" },
{ category: "D", name: "devid" },
{ category: "E", name: "sam" },
{ category: "F", name: "sam" },
{ category: "G", name: "sam" }
]
};
const groupedByCategory = person.con.reduce((acc, item) => {
if (!Array.isArray(acc[item.category])) {
acc[item.category] = [];
}
acc[item.category].push(item.name);
return acc;
}, {});
const Comp = () => {
return Object.entries(groupedByCategory).map(([category, names]) => {
return (
<div>
<h3>{category}</h3>
<ul>
{names.map((name) => (
<li>{name}</li>
))}
</ul>
</div>
);
});
};
添加回答
举报