Reputation: 793
I currently have an IMAGES array that is supposed to display images if the index exists. With the current implementation, I have the images are being displayed if an index with an image exists and for index without images, a black screen gets displayed.
How do I change my code so that if an image doesn't exist it does not get added to the array?
Here is my code:
const IMAGES = [
post.images[1]
? {
url: post.images[1].url,
}
: [],
post.images[2]
? {
url: post.images[2].url,
}
: [],
post.images[3]
? {
url: post.images[3].url,
}
: [],
post.images[4]
? {
url: post.images[4].url,
}
: [],
post.images[5]
? {
url: post.images[5].url,
}
: [],
post.images[6]
? {
url: post.images[6].url,
}
: [],
post.images[7]
? {
url: post.images[7].url,
}
: [],
];
Upvotes: 0
Views: 90
Reputation: 21
let IMAGES = [];
post?.images &&
post.images.length > 0 &&
post.images.map((eachImage, index) => {
if ("url" in eachImage) {
IMAGES.push(eachImage.url);
}
});
Upvotes: 2
Reputation: 394
This should do what you want:
const IMAGES = [];
post.images && post.images.map(image => {
if(image && image.url) {
IMAGES.push({url: image.url})
}
})
Upvotes: 1
Reputation: 1450
const posts = {
images: [
{
url: "https//1",
},
{
url: "https//2",
},
{},
{
url: "https//3",
},
null,
{
url: "https//4",
},
],
};
const images = posts.images.map((item) => (item && item.url ? {url:item.url} : []));
console.log(images)
Upvotes: 0