简体   繁体   中英

Variable not getting replaced with a value on JSON generation in JavaScript?

_postData : function ()
{
    var fieldName = "day";

    var day = /*returns an object from the back end business service*/

    var value = day.getValue();

    if (value)
    {
        return {
            fieldName : value
        };
    }
}

The problem is, even though fieldName is actually "day", when the JSON payload gets returned and printed, I am seeing literally:

{
   fieldName: "16"
}

So for some reason that variable's name is being printed, not it's actual string value. What I want is:

{
   day: "16"
}

This is not JSON, it's Javascript object literals. And when you put a symbol on the left hand side of a property in a Javascript object literal, that is used as the property name, not any string that the variable of that name might evaluate to. In other words, {fieldName: 16} is exactly equivalent to {"fieldName": 16}

Instead of doing this:

return {
     fieldName : value
};

You could do something like this:

var obj = {};
obj[fieldName] = value;
return obj;

In the second one, if fieldName is a variable containing a string "foo" , then the resulting object will look like {foo: 16}

As Kiyura said, this is not the way defining objects works. Your current code is essentially creating an object with a fieldName property not a day property. Instead you need to do something like this:

_postData : function ()
{
    var fieldName = "day";

    var day = /*returns an object from the back end business service*/

    var value = day.getValue();

    if (value)
    {
        var ret={};
        ret[fieldName]=value;
        return ret;
    }
}

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