简体   繁体   中英

Why can't I access object properties in javascript?

I've a simply loop in node.js:

exports.sample = function (req, res) {
    var images = req.query.images;
    images.forEach(function (img) {
        console.log(img);
        console.log(img.path, img.id);
        console.log(img);
    });
    res.end();
};

The result is:

{"id":42,"path":"gGGfNIMGFK95mxQ66SfAHtYm.jpg"}
undefined undefined
{"id":42,"path":"gGGfNIMGFK95mxQ66SfAHtYm.jpg"}

I can access the properties in the client side but not on the server side.

Can someone help me to understand what's happening? Why can't I access my object properties?

As others have pointed out, most probably img is in string form. You need to run JSON.parse() on it to convert it to an object, so you can access its properties.

Here I have written the JSON.parse() inside a check ie only when img is of type "string" should you parse it. But I think, you will always be getting img as a string, so you can simply parse it without the check.

exports.sample = function (req, res) {
    var images = req.query.images;
    images.forEach(function (img) {
        console.log(img);

        //Here, this code parses the string as an object
        if( typeof img === "string" )
          img = JSON.parse( img );

        console.log(img.path, img.id);
        console.log(img);
    });
    res.end();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM