0

I want to create an gallery form an object.

Angular - typescript

I have this function:

showGallery(index: number) {
    let prop = {
        images: [
            {path: 'https://web-service/attach/file/' + this.PIC[0].guid},
            {path: 'https://web-service/attach/file/' + this.PIC[1].guid},
            {path: 'https://web-service/attach/file/' + this.PIC[2].guid}
        ],
        index
    };
    this.gallery.load(prop);
}

And I don't know how to make loop inside this function.

I have an PIC array with GUID's of pictures. PIC is created by API call to database and of course there is always different number of pictures.

Can someone explain me, why I cant do it just like this:

showGallery(index: number) {
        let prop = {
            images: [
                for(var PICs of PIC){
                {path: 'https://web-service/attach/file/' + PICs.guid}
           }
            ],
            index
        };
        this.gallery.load(prop);
    }

Is that have something in common with scoping?

2
  • 3
    for loops do not return values.... Commented Jan 20, 2021 at 21:19
  • 3
    images: this.PIC.map(PICS => ...build your object and return it...) Commented Jan 20, 2021 at 21:20

1 Answer 1

1

If you need to iterate over every element of an array, map is really useful. It returns a new array of objects as specified by the return value of the function you pass it. In your code it would look like this:

showGallery(index: number) {
    let prop = {
        images: this.PIC.map(p => { path: 'https://web-service/attach/file/' + p.guid }),
        index
    };
    this.gallery.load(prop);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.