Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  171] [ 3]  / answers: 1 / hits: 32340  / 6 Years ago, tue, july 31, 2018, 12:00:00

I am trying to map over array of objects which each array contains another nested array of objects. However, the map does not work on the nested array. How do I map over the contents of the nested array while keeping all the content under the same title of the parent object?


Fiddle: https://jsfiddle.net/69z2wepo/249197/


The data structure looks like:


[
{
title: "title1",
content: [
{
imageUrl: "http://placehold.it/300x300",
title: "Campaigns",
description:
"Short description explaining the use of this design in a single sentence."
},
{
imageUrl: "http://placehold.it/300x300",
title: "Events",
description:
"Short description explaining the use of this design in a single sentence."
},
{
imageUrl: "http://placehold.it/300x300",
title: "General",
description:
"Short description explaining the use of this design in a single sentence."
}
]
},
{
title: "title2",
content: [
{
imageUrl: "http://placehold.it/300x300",
title: "Video Template A",
description:
"Short description explaining the use of this design in a single sentence."
},
{
imageUrl: "http://placehold.it/300x300",
title: "Video Template A",
description:
"Short description explaining the use of this design in a single sentence."
}
]
}
];

The map looks like


{dataItems.map((item, index) => {
return (
<h1>{item.title}</h1>
// for each item, loop over the content array objects
<img src={item.content.imageUrl} />
<h3>{item.content.title}</h3>
<h3>{item.content.description}</h3>
<hr />
);
})}

More From » arrays

 Answers
6

Since each element has a content array, you must map over content as well.



Example



{dataItems.map((item, index) => (
<div key={index}>
<h1>{item.title}</h1>
{item.content.map((c, i) => (
<div key={i}>
<img src={c.imageUrl} />
<h3>{c.title}</h3>
<h3>{c.description}</h3>
<hr />
</div>
))}
</div>
))}

[#53841] Thursday, July 26, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ernest

Total Points: 332
Total Questions: 92
Total Answers: 98

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
ernest questions
Sat, Jun 12, 21, 00:00, 3 Years ago
Tue, Sep 22, 20, 00:00, 4 Years ago
;