2

I'm looping through a nested object to get a some data. This is working, but I can't seem to return the data and use it elsewhere.

I've tried putting the loop in a promise and couldn't get anywhere either. What am I doing wrong?

data: any = {
    '1234': {
        url: 'https://example1.com/',
        path: 'uploads',
        link: 'https://example1.com/uploads',
    },
    '5678': {
        url: 'https://example2.com/',
        path: 'uploads',
        link: 'https://example2.com/uploads',
    }
}


onSubmit(formData) {

    this.formdata = formData;

    Object.keys(this.data).forEach(key => {
        if (key == this.formdata.pin) {
            const url = this.data[key].url;
            // have also tried this.url to no avail
        }
    });

    // says undefined
    console.log(url);

    // set up headers, etc...

    // I need to use here
    this.http.post(url, body, head)
    ...
}
wintech
  • 71
  • 1
  • 9

2 Answers2

2
onSubmit(formData) {

this.formdata = formData;
let url; // Define here so that its accessible
Object.keys(this.data).forEach(key => {
    if (key === this.formdata.pin) {
         url = this.data[key].url;
        // have also tried this.url to no avail
    }
});

// Now url is in scope
console.log(url);

    ...
}
dota2pro
  • 7,220
  • 7
  • 44
  • 79
  • 1
    This solution moves `url` to the `onSubmit` block scope and can therefore be used/accessed in your `console.log` statement – Rastalamm May 28 '19 at 22:22
1

Switching your forEach to a map can simplify this; map return values, whereas forEach does not.

Old:

Object.keys(this.data).forEach(key => {
    if (key == this.formdata.pin) {
        const url = this.data[key].url;
    }
});

// says undefined
console.log(url);

New: (I've also added a === in here based on the comment below)

const urls = Object.keys(this.data).map(key => {
    if (key === this.formdata.pin) {
        return this.data[key].url;
        // have also tried this.url to no avail
    }
});

console.log(urls);

map docs and forEach docs

Rastalamm
  • 1,712
  • 3
  • 23
  • 32