1

How do i get the value of myObject.myname, myObject.myage from the function getval? It returns undefined when i console.log it. Btw I'm using node js. Thanks.

    var post = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (data) {
        console.log('Response: ' + data);

    var myObject = JSON.parse(data);

        console.log('----------------------------------------------');
        console.log(myObject.myname);
        console.log(myObject.myage);
        console.log('----------------------------------------------');
        });
    });

    function getVal() {
        //some code here
        console.log(myObject.myname);
        console.log(myObject.myage);
    }

2 Answers 2

2
  1. Declare myObject outside the anonymous function you pass to request (var myObject) instead of inside it. At present it is a local variable.
  2. Call getVal() after the HTTP response has been received (otherwise it won't have been set yet). At present you aren't calling it at all.
Sign up to request clarification or add additional context in comments.

Comments

0

There is a scope issue, can you try this instead?

var myObject = {};
var post = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (data) {
    console.log('Response: ' + data);

    myObject = JSON.parse(data);

    console.log('----------------------------------------------');
    console.log(myObject.myname);
    console.log(myObject.myage);
    console.log('----------------------------------------------');
    });
});

function getVal() {
    //some code here
    console.log(myObject.myname);
    console.log(myObject.myage);
}

2 Comments

By the way myObject contains myname, myage, and etc.
That should be no problem provided the object is declared in a scope which is accessible by getVal

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.