How to display data from an array with nested objects?
There are a bunch of objects in the array that have nesting, I tried to loop the render, but it didn’t help
const DATA = [
{
title: "Apple",
fields: {
title: "iPhone",
fields: {
title: "14 pro",
fields: {},
},
},
},
{
title: "Xiaomi",
fields: {
title: "phone",
fields: {
title: "MI 5",
fields: {},
},
},
},
];
const itemsRender = (item, idx) => {
const key = Object.keys(item).at(-1);
return (
<div key={idx}>
<p>{item[key].title}</p>
{!isEmpty(item[key]?.fields) &&
Object.values(item[key]?.fields).map(itemsRender)}
</div>
);
};
return <>{DATA.map(itemsRender)}</>;
3
Answers
Maybe something like this:
Added the subIdx parameter to the recursive call of itemsRender to provide a unique key for each nested item.
I have created an array of objects called DATA. Each object has two properties: title and fields. The fields property is an object that contains nested properties. It then defined a function called itemsRender that takes an object and an index as its arguments. Finally, using the map() method to iterate over the DATA array and call the itemsRender function for each object.
We can pull specific data with "dot" notation. Then using
.map
method to iterate through an array of objects.Note: just in case I modified the keys to make it more legible.