0

The issue only happens when the associative array is programmatically apposed to via a literal definition. Using stringify on a literal definition works.

Trying to understand, I used this to test with a literal definition.

var test = {
    voice : { state : 'Ready' }
};
console.log('Stringify test: ' + JSON.stringify(test));

And the output is exactly what I'd expect:

Stringify test: {"voice":{"state":"Ready"}}

This isn't happening when I initialize it programmatically. I should mention that the variable is a private member of an object that I've created, which has accessor/getter methods. Within the constructor, I have:

var states = {};

this.getStates = function()
{
    return states;
}

this.setState = function(newState, mediaType)
{
    states[mediaType] = newState
}

Now I run the same test.

customObj.setState('{ state: 'Ready' }', 'voice');
var test = customObj.getStates();

console.log('Stringify test: ' + JSON.stringify(test));

And the output is not what I expect:

Stringify Test: []

Lastly I double check what the test variable has with:

for(var x in test)
{
    console.log('State in test: ' + x);
    console.log('Value of ' + x + ': ' + JSON.stringify(test[x])); 
}

And with that I get:

State in test: voice
Value of voice: {"state":"Ready"}

OK, so that's telling me that it contains what I'm expecting, but stringify() doesn't format it. Now, I'm left slightly confused what's going on.

3
  • 2
    Typo? Well this line is wrong customObj.setState('{ state: 'Ready' }', 'voice'); You really wanted a string??? Commented May 9, 2013 at 15:30
  • That line isn't even valid JS because of the mismatched quotes, so this must not be the OP's real code. Commented May 9, 2013 at 15:30
  • 1
    Fixing the typo and it runs: jsfiddle.net/Mn5gn Commented May 9, 2013 at 15:32

1 Answer 1

2

I am not sure how you are creating your customObj but the following works:

var CustomObj = function () {
    var states = {};

    this.getStates = function()
    {
        return states;
    }

    this.setState = function(newState, mediaType)
    {
        states[mediaType] = newState
    }
};

var customObj = new CustomObj();
customObj.setState({ state: 'Ready' }, 'voice');

var test = customObj.getStates();
console.log('Stringify test: ' + JSON.stringify(test));

It outputs:

Stringify test: {"voice":{"state":"Ready"}}
Sign up to request clarification or add additional context in comments.

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.