0

I am using the following method to basically create a JSON string.

var saveData = {};
saveData.a = 2;
saveData.c = 1;

However the .a and .c don't cut it for what I need to do, I need to replace these with strings. So something like..

var name = 'wibble';
saveData.name = 2;

This would get accessed with

saveData.wibble

Does anyone know how this could be achieved?

3 Answers 3

4
var name = "wibble";
saveData[name] = 2;

alert(saveData.wibble);

Note that, in JavaScript, the following notations are equivalent:

obj.key
obj["key"]
Sign up to request clarification or add additional context in comments.

Comments

2

Use the map accessor:

var name = 'wibble'
saveData[name] = 2

Comments

1

You can access Javascript objects using a dictionary notation:

var name = 'wibble';
saveData[name] = 2;

saveData.wibble is now 2.

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.