0

Below I have the following code:

var imageType = "BoxArt";
var uploadReason = "New season";
var fileKey = "b2fc";

alert("imageType = " + imageType);
alert("uploadReason = " + uploadReason);
alert("fileKey = " + fileKey);

var iVO = { "images":{}};
var thisImage = fileKey;
iVO["images"][thisImage.fileKey] = thisImage;
iVO["images"][thisImage.imageType] = imageType;
iVO["images"][thisImage.uploadReason] = uploadReason;

alert("iVO['images'][thisImage.imageType] = " + iVO["images"][thisImage.imageType]);
alert("iVO['images'][thisImage.uploadReason] = " + iVO["images"]    [thisImage.uploadReason]);
alert("iVO['images'][thisImage.fileKey] = " + iVO["images"][thisImage.fileKey]);
alert("JSON.stringify(iVO):\n" + JSON.stringify(iVO));

When I execute this I get the following output:

imageType = "BoxArt"
uploadReason = "New season"
fileKey = "b2fc"
iVO['images'][thisImage.imageType] = "New season"
iVO['images'][thisImage.uploadReason] = "New season"
iVO['images'][thisImage.fileKey] = "New season"
JSON.stringify(iVO):
{"images"}:{"undefined":"New season"}}

What is going on here?!?!?

The first three alerts (showing imageType, uploadReason, and fileKey assignments) are as expected, but the iVO object is not acting at all like I expected. The JSON.stringify method is the normal json2.js method, and I haven't modified it.

Why is "New season" showing up as every iVO["images"] field value? Why aren't the iVO assignments working properly?!? What do I need to do to fix them?

The desired output of JSON.stringify(iVO) would be (in pretty-print form):

{
    "images":
    {
        "b2fc":
        {
            "imageType":"BoxArt",
            "uploadReason":"New season",
            "fileKey":"b2fc"
        }
    }
}

Thanks in advance!

2 Answers 2

1

for sure, where you defined

iVO["images"][thisImage.fileKey] = thisImage;
iVO["images"][thisImage.imageType] = imageType;
iVO["images"][thisImage.uploadReason] = uploadReason;

thisImage is a string by previous assignment to fileKey so thisImage.fileKey, thisImage.imageType and thisImage.uploadReason are invalid references

probably you want to do something like iVO["images"][fileKey]["imageType"] = imageType

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

Comments

1

I think you want

iVO['images'][thisImage] = {
         "imageType":"BoxArt",
        "uploadReason":"New season",
        "fileKey":"b2fc"
    };

which I would write as

 iVO.images[thisImage] = {
         "imageType":"BoxArt",
        "uploadReason":"New season",
        "fileKey":"b2fc"
    };

There is no magic auto-unnesting/vivification of sub-objects for field names with dots in them.

Comments

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.