Reputation: 23
I have an array with 8 objects. I am using a loop to get the values of each items. And I want to display them in a div in my html file. I'd like to display only 4 of them (for the moment! but after I want to replace those images automatically when I delete them).
I know I could use a splice() method or a slice() method. But I'd like to know if it is possible to do it whitout creating a new array ? Because I want my for loop transforming all the objects into images in one time.
const data = [
{
image_name: "Image1",
image_id: "0",
source: "images/img1.png",},
{
image_name: "Image2",
image_id: "1",
source: "images/img2.png",
},
{
image_name: "Image3",
image_id: "2",
source: "images/img3.png",
},
{
image_name: "Image4",
image_id: "3",
source: "images/img4.png",
},
{
image_name: "Image5",
image_id: "4",
source: "images/img5.png",
},
{
image_name: "Image6",
image_id: "5",
source: "images/img6.png",
},
{
image_name: "Image7",
image_id: "6",
source: "images/img7.png",
},
{
image_name: "Image8",
image_id: "7",
source: "images/img8.png",
}
]
for (let i = 0; i < data.length; i++) { // data.length returns 8
// creation of the images
let images = document.createElement('img')
images.setAttribute('class', 'image')
document.querySelector('.container-image-to-place').append(images)// It displays automatically the 8 images
}
images = document.querySelectorAll('.image')
// assign each values to the good image
data.forEach(({source, image_name, image_id}, i) => {
images[i].src = source
images[i].alt = image_name
images[i].id = image_id
})
<body>
<div class="container-image-to-place">
<!-- the images are displayed here -->
</div>
</body>
Upvotes: 0
Views: 474
Reputation: 11912
I don't quite understand what you are trying to achieve. But if you want to process the first 4 items without modifying the array you can do...
data.forEach(({source, image_name, image_id}, i) => {
if (i < 4) {
images[i].src = source
images[i].alt = image_name
images[i].id = image_id
}
});
This however isn't particularly elegant though as if you had an array of 1000 object it would need to perform the condition for each one. As you suggest it would be better to use .slice
...
// untested!
data.slice(0, 4).forEach(({source, image_name, image_id}, i) => {
images[i].src = source
images[i].alt = image_name
images[i].id = image_id
});
This won't alter your data
array but will create a new copy of the first 4 items.
Upvotes: 1
Reputation: 26
Using a for loop is useful if you want to loop through all your images, however if you only want to loop through 4 of them why not use a while loop like this:
while (i < 4) {
// code block to be executed
i++;
}
Upvotes: 0