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)
    ...
}
2
  • use map() instead of forEach() Commented May 28, 2019 at 22:10
  • url is undefined in your above example as it is limited in scope. Commented May 28, 2019 at 22:22

2 Answers 2

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);

    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

This solution moves url to the onSubmit block scope and can therefore be used/accessed in your console.log statement
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

1 Comment

Better to use === than ==

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.