I have an array of object like below -
{
name:"Thor",
universe:"Marvel",
type:"God"
},
{
name:"Batman",
universe:"DC",
type:"Human"
},
{
name:"Iron man",
universe:"Marvel",
type:"Human"
},
];
Now, let's suppose that I want to render the objects such that the details of type Human are together, and the details of type God are together.
Basically, I want to display data based on the type property like below -
**Human**
name: Batman universe:DC
name: Iron man universe:Marvel
**God**
name: Thor universe: Marvel
I hope the problem statement is clear. Many thanks in advance.
I can help you with classification. You can do render your self.
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)
}
Category like:
{
"God":[
{
"name":"Thor",
"universe":"Marvel",
"type":"God"
}
],
"Human":[
{
"name":"Batman",
"universe":"DC",
"type":"Human"
},
{
"name":"Iron man",
"universe":"Marvel",
"type":"Human"
}
]
}
I would first format the data type to an easy to use data type: See example below:
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>
);
}
Try this, do map on finalArray variable and render name, universe etc.
const data = [
{
name:"Thor",
universe:"Marvel",
type:"God"
},
{
name:"Batman",
universe:"DC",
type:"Human"
},
{
name:"Iron man",
universe:"Marvel",
type:"Human"
},
];
const _human = data.filter(item => item.type === "Human");
const _god = data.filter(item => item.type === "God");
const finalArray = [..._human, ..._god];
console.log('>>>human', _human);
console.log('>>>god', _god);
console.log('>>>merge', finalArray);